JavaWeb购物系统
项目描述
基于B/S三层架构设计的购物系统,可以更好地符合“高内聚,低耦合”的设计思想。表现层(UI)通过JSP在浏览器上实现界面展示,通过Servlet接受用户请求并生成验证码等实时信息;数据访问层(DAL)通过JDBC对DBMS进行访问;二者之间的业务逻辑层(BLL)通过Service进行连接。同时面向接口编程提高规范化。这只是我自己用两三天的时间做的小项目,距离真正的购物系统差距还是相当大的,仅供初学者参考,很多逻辑缺陷不必太纠结。
如果只需要代码可直接通过书签栏跳转至相关文件。
项目演示
系统首页
这是购物系统首页,仿照华为商城设计,具体实现借助于Bootstrap,商品信息通过后台数据库读取
如果此时点击商品会通过Session中的登陆信息判断登陆状态,若未登录则提示登录
注册与登录
我们先注册再登录,这里注册斯维因的相关信息。登录页面与注册页面通过js实现正则验证,通过Servlet实现验证码相关功能,背景渐变色借助于WebGradients选取
用刚刚注册的用户进行登录
商品详情
登陆后我们回到首页,点击商品,进入商品详情页
购物车信息
将商品加入购物车后查看购物车,这里会一致显示当前登录用户信息
订单详情
我们提交订单后再查看订单。这里借助jQuery做了一个下拉框,可以查看后台数据库关于此用户的全部订单的全部信息,这里提交订单相当于付款,所以未设退货功能,因此数据删除只能借助于后台数据库
注销
最后点击注销
部分代码
index.jsp
<%--
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖保佑 永无BUG
--%>
<%@ page import="util.CustomUtil" %>
<%@ page import="entity.People" %>
<%@ page import="entity.Goods" %>
<%@ page import="service.GoodsService" %>
<%@ page import="service.impl.GoodsServiceImpl" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>购物系统主页</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<%=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"%>">
<link rel="stylesheet" href="./css/index.css">
<link rel="stylesheet" href="./css/bootstrap.min.css"/>
<script src="./js/jquery-3.5.1.min.js"></script>
<script src="./js/bootstrap.min.js"></script>
</head>
<body>
<%
People now_people = new People(0, null, null, null, null, 0);
if (session.getAttribute("now_people") != null) {
now_people = (People) session.getAttribute("now_people");
}
CustomUtil.outPosition("yellow", "index.jsp");
CustomUtil.outParameter("yellow", "now_people", now_people.toString());
CustomUtil.outParameter("yellow", "base href", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/");
/*用于显示商品信息*/
Goods goods = new Goods();
GoodsService goodsService = new GoodsServiceImpl();
%>
<script> function onClick() {
<% if (now_people.getId() == 0) {
out.print("alert(\"请先登录!\");"); out.print("return false;"); } %> } </script>
<!-- 导航栏区域 -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"><!-- <nav class="导航栏 导航栏样式 导航栏位置" 标识这是一个导航容器> -->
<div class="div">
<ul class="nav navbar-nav"><!-- 定义无序列表 -->
<li class="active"><a href="./index.jsp">系统首页</a></li>
<li><a href="#">华为官网</a></li>
<li><a href="#">荣耀官网</a></li>
<li><a href="#">花粉俱乐部</a></li>
<li><a href="#">企业购</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<%
String str_navbar_right;
if (now_people.getId() == 0) {
str_navbar_right =
"<li class=\"dropdown\">" +
"<a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">" +
"登陆/注册" +
"<span class=\"caret\"></span>" +
"  " +
"</a>" +
"<ul class=\"dropdown-menu\">" +
"<li><a href=\"./page/login.jsp\">登陆</a></li>" +
"<li class=\"divider\"></li>" +
"<li><a href=\"./page/register.jsp\">注册</a></li>" +
"</ul>" +
"</li>";
}
else {
str_navbar_right =
"<li><a href=\"#\">" + "当前登录:" + now_people.getName() + "</a></li>" +
"<li><a href=\"./page/logoutCorrect.jsp\">注销</a></li>" +
"<li><a href=\"./page/shopCar.jsp\">购物车</a></li>" + " ";
}
%>
<%=str_navbar_right %>
</ul>
</div>
</nav>
<!-- 热销单品区域 -->
<div class="main">
<br />
<h2 style="text-align: center;">热销单品</h2>
<br />
<div class="left">
<a href="#"><img src="png/phone0.png" alt=""></a>
</div>
<div class="right">
<a href="./page/goods.jsp?goods_id=101" onclick="return onClick()">
<div>
<%
goods = goodsService.find(101);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
<a href="./page/goods.jsp?goods_id=102" onclick="return onClick()">
<div>
<%
goods = goodsService.find(102);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
<a href="./page/goods.jsp?goods_id=103" onclick="return onClick()">
<div>
<%
goods = goodsService.find(103);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
<a href="./page/goods.jsp?goods_id=104" onclick="return onClick()">
<div>
<%
goods = goodsService.find(104);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
<a href="./page/goods.jsp?goods_id=105" onclick="return onClick()">
<div>
<%
goods = goodsService.find(105);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
<a href="./page/goods.jsp?goods_id=106" onclick="return onClick()">
<div>
<%
goods = goodsService.find(106);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
<a href="./page/goods.jsp?goods_id=107" onclick="return onClick()">
<div>
<%
goods = goodsService.find(107);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
<a href="./page/goods.jsp?goods_id=108" onclick="return onClick()">
<div>
<%
goods = goodsService.find(108);
%>
<div class="images"><img src="<%=goods.getImage()%>" alt=""></div>
<div class="name">
<h3><%=goods.getName()%></h3>
</div>
<div class="explain">
<p><%=goods.getInfo_brief()%></p>
</div>
<div class="price">
<div class="newprice">
<p><%=goods.getNew_price()%>元</p>
</div>
<div class="oldprice">
<p><%=goods.getOld_price()%>元</p>
</div>
</div>
</div>
</a>
</div>
</div>
<!-- 其他商品区域 -->
<div class="main">
<br />
<h2 style="text-align: center;">其他商品</h2>
<br />
<div class="middle">
<a href="#"><img src="./png/other0.png" alt=""></a>
<a href="#"><img src="./png/other5.png" alt=""></a>
</div>
<div class="right">
<a href="#">
<div>
<div class="images"><img src="./png/other1.png" alt=""></div>
<div class="name">
<h3>HUAWEI MateBook X</h3>
</div>
<div class="explain">
<p>晒单赠内胆包+三期免息</p>
</div>
<div class="price">
<div class="nowprice">
<p>8999元</p>
</div>
</div>
</div>
</a>
<a href="#">
<div>
<div class="images"><img src="./png/other2.png" alt=""></div>
<div class="name">
<h3>HUAWEI MateBook 14</h3>
</div>
<div class="explain">
<p>2K触控屏轻薄本</p>
</div>
<div class="price">
<div class="newprice">
<p>6399元起</p>
</div>
<div class="oldprice">
<p>6999元</p>
</div>
</div>
</div>
</a>
<a href="#">
<div>
<div class="images"><img src="./png/other3.png" alt=""></div>
<div class="name">
<h3>荣耀猎人游戏本 V700</h3>
</div>
<div class="explain">
<p>强劲游戏性能</p>
</div>
<div class="price">
<div class="newprice">
<p>7499元起</p>
</div>
<div class="oldprice">
<p>7999元</p>
</div>
</div>
</div>
</a>
<a href="#">
<div>
<div class="images"><img src="./png/other4.png" alt=""></div>
<div class="name">
<h3>HUAWEI MateBook D 14</h3>
</div>
<div class="explain">
<p>多屏协同180度开合</p>
</div>
<div class="price">
<div class="nowprice">
<p>5299元</p>
</div>
</div>
</div>
</a>
<a href="#">
<div>
<div class="images"><img src="./png/other6.png" alt=""></div>
<div class="name">
<h3>HUAWEI MatePad 10.8</h3>
</div>
<div class="explain">
<p>享三期免息</p>
</div>
<div class="price">
<div class="nowprice">
<p>2399元</p>
</div>
</div>
</div>
</a>
<a href="#">
<div>
<div class="images"><img src="./png/other7.png" alt=""></div>
<div class="name">
<h3>HUAWEI MatePad Pro</h3>
</div>
<div class="explain">
<p>享三期免息</p>
</div>
<div class="price">
<div class="newprice">
<p>3799元起</p>
</div>
<div class="oldprice">
<p>3999元</p>
</div>
</div>
</div>
</a>
<a href="#">
<div>
<div class="images"><img src="./png/other8.png" alt=""></div>
<div class="name">
<h3>[Wifi6+]荣耀平板V6</h3>
</div>
<div class="explain">
<p>现货速发</p>
</div>
<div class="price">
<div class="nowprice">
<p>2798元</p>
</div>
</div>
</div>
</a>
<a href="#">
<div>
<div class="images"><img src="./png/other9.png" alt=""></div>
<div class="name">
<h3>华为畅享平板 2</h3>
</div>
<div class="explain">
<p>享三期免息</p>
</div>
<div class="price">
<div class="nowprice">
<p>1799元</p>
</div>
</div>
</div>
</a>
</div>
</div>
<!-- 底部导航栏 -->
<div class="footer">
<div class="center">
<div class="zuo">
<div class="ph">
<p>隐私声明 服务协议 COOKIES Copyright © 2012-2020 华为终端有限公司 版权所有<br />粤ICP备19015064号 | 粤公网安备 44190002003939号</p>
</div>
<div class="btn"><a href="#">下载APP</a></div>
</div>
<div class="you">
<div>
<dl>
<dt>维修与技术支持</dt>
<br>
<a href="#"><dd>服务点</dd></a>
<a href="#"><dd>预约维修</dd></a>
<a href="#"><dd>手机寄修</dd></a>
<a href="#"><dd>备件价格查询</dd></a>
<a href="#"><dd>上门服务</dd></a>
</dl>
</div>
<div>
<dl>
<dt>保修与退换货</dt>
<br>
<a href="#"><dd>保修政策</dd></a>
<a href="#"><dd>退换货政策</dd></a>
<a href="#"><dd>保修状态查询</dd></a>
<a href="#"><dd>配件防伪查询</dd></a>
</dl>
</div>
<div>
<dl>
<dt>购物相关</dt>
<br>
<a href="#"><dd>购物指南</dd></a>
<a href="#"><dd>配送方式</dd></a>
<a href="#"><dd>支付方式</dd></a>
<a href="#"><dd>常见问题</dd></a>
</dl>
</div>
</div>
</div>
</div>
</body>
</html>
JdbcUtils.java
用于加载驱动并获得与数据库的连接的工具类
package util;
import java.sql.*;
public class JdbcUtil {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String url =
"jdbc:mysql://localhost:3306/shoppingsystem?characterEncoding=utf-8";//连接字符串
private static final String user = "root";
private static final String password = "123";
private static Connection connection;
/** * 建立连接 * @return 返回获得的连接 */
public static Connection getConnection() {
try {
Class.forName(driver);//通过反射机制加载驱动
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection = DriverManager.getConnection(url, user, password);//获得连接
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
/** * 关闭连接 */
public static void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
People.java
与数据库中用户表相匹配的用户类
package entity;
public class People {
private int id;//用户编号
private String password;//用户密码
private String name;//用户姓名
private String email;//用户邮箱
private String address;//用户地址
private int status;//用户状态
public People() {
super();
}
public People(int id, String password, String name, String email, String address, int status) {
this.id = id;
this.password = password;
this.name = name;
this.email = email;
this.address = address;
this.status = status;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", password='" + password + '\'' +
", name='" + name + '\'' +
", email='" + email + '\'' +
", address='" + address + '\'' +
", status=" + status +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
PeopleDao.java
对用户信息进行相关操作的接口
package dao;
import entity.People;
public interface PeopleDAO {
/** * 插入用户数据 * @return 插入行数 */
public abstract int doInsert(int id, String password, String name, String email, String address, int status);
public abstract int doDelete(int id, String password);
public abstract int doUpdate(int id, String password, String name, String email, String address, int status);
/** * 根据用户编号和密码查询用户数据 * @return 查询到的用户实体 */
public abstract People findByLogin(int id, String password);
/** * 根据用户编号查询用户数据 * @return 查询到的用户实体 */
public abstract People findById(int id);
}
PeopleDaoImpl.java
对上述接口的实现
package dao.impl;
import dao.PeopleDAO;
import entity.People;
import util.CustomUtil;
import util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PeopleDAOImpl implements PeopleDAO {
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
@Override
public int doInsert(int id, String password, String name, String email, String address, int status) {
int result = 0;
String sql = "INSERT INTO `people` VALUES (" +
id +
", '" + password +
"', '" + name +
"', '" + email +
"', '" + address +
"', '" + status +
"');";
connection = JdbcUtil.getConnection();
try {
preparedStatement = connection.prepareStatement(sql);
result = preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtil.closeAll(connection, preparedStatement, resultSet);
}
CustomUtil.outPosition("blue", "PeopleDAOImpl.doInsert()");
CustomUtil.outParameter("blue", "sql", sql);
CustomUtil.outParameter("blue", "result", String.valueOf(result));
return result;
}
@Override
public int doDelete(int id, String password) {
return 0;
}
@Override
public int doUpdate(int id, String password, String name, String email, String address, int status) {
return 0;
}
@Override
public People findByLogin(int id, String password) {
People people = new People();
String sql = "select * from `people` where `id` = '" + id + "' and password = '" + password + "';";
connection = JdbcUtil.getConnection();
try {
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
people.setId(resultSet.getInt(1));
people.setPassword(resultSet.getString(2));
people.setName(resultSet.getString(3));
people.setEmail(resultSet.getString(4));
people.setAddress(resultSet.getString(5));
people.setStatus(resultSet.getInt(6));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtil.closeAll(connection, preparedStatement, resultSet);
}
CustomUtil.outPosition("blue", "PeopleDAOImpl.findByLogin()");
CustomUtil.outParameter("blue", "sql", sql);
CustomUtil.outParameter("blue", "people", people.toString());
return people;
}
public People findById(int id) {
People people = new People();
String sql = "select * from `people` where `id` = '" + id + "';";
CustomUtil.outPosition("blue", "PeopleDaoImpl.findById()");
CustomUtil.outParameter("blue", "id", String.valueOf(id));
connection = JdbcUtil.getConnection();
try {
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
people.setId(resultSet.getInt(1));
people.setPassword(resultSet.getString(2));
people.setName(resultSet.getString(3));
people.setEmail(resultSet.getString(4));
people.setAddress(resultSet.getString(5));
people.setStatus(resultSet.getInt(6));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtil.closeAll(connection, preparedStatement, resultSet);
}
CustomUtil.outPosition("blue", "PeopleDAOImpl.findById()");
CustomUtil.outParameter("blue", "sql", sql);
CustomUtil.outParameter("blue", "people", people.toString());
return people;
}
}
PeopleService.java
在业务逻辑层中将表现层与数据访问层进行连接,由于项目本身并不复杂,所以只是简单实现了方法传递
package service;
import entity.People;
public interface PeopleService {
/** * 用户注册 * @return 0:注册成功,1:重复注册,2:其他原因 */
public abstract int register(People people);
/** * 用户登录 * @return true:注册成功,false:注册失败 */
public abstract boolean login(People people);
/** * 根据id查找用户 * @return 查询成功返回目标实体,失败返回{0, null, null, null, null, 0} */
public abstract People find(int id);
public abstract boolean alter(People people);
}
PeopleService.java
对上述接口的实现
package service.impl;
import dao.PeopleDAO;
import dao.impl.PeopleDAOImpl;
import entity.People;
import service.PeopleService;
import util.CustomUtil;
public class PeopleServiceImpl implements PeopleService {
private PeopleDAO peopleDAO = new PeopleDAOImpl();//不实例化会导致空指针异常
@Override
public int register(People people) {
CustomUtil.outPosition("red", "PeopleServiceImpl.register()");
CustomUtil.outParameter("red", "people", people.toString());
if (peopleDAO.findById(people.getId()).getId() == 0) {
if (peopleDAO.doInsert(
people.getId(), people.getPassword(), people.getName(),
people.getEmail(), people.getAddress(), people.getStatus()) == 1) {
return 0;
} else {
return 2;
}
}
return 1;
}
@Override
public boolean login(People people) {
if (peopleDAO.findByLogin(people.getId(), people.getPassword()).getId() != 0) {
return true;
}
return false;
}
@Override
public People find(int id) {
return peopleDAO.findById(id);
}
@Override
public boolean alter(People people) {
return false;
}
}
CheckCodeServlet.java
在内存中生成验证码图片并输出到客户端
package servlet;
import util.CustomUtil;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@WebServlet(name = "CheckCodeServlet", urlPatterns = "/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static int width=70;
private static int height=25;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/** * request是客户端浏览器发出的请求被封装形成的一个HttpServletRequest公共接口类对象 * session对象存储特定用户会话所需的属性及配置信息,这样当用户在应用程序的Web页之间跳转时,存储在session对象中的变量将不会丢失,而是在整个用户会话中一直存在下去 * getSession()与getSession(true)一样,获取request对象关联的session对象,如果没有session,则返回一个新的session */
HttpSession session=request.getSession();
response.setContentType("image/jpeg");//设置生成的文档类型为jpg
ServletOutputStream servletOutputStream = response.getOutputStream();
/*设置浏览器不要缓存此图片*/
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
/** * 创建内存图片并获得其图形上下文 * Image是一个抽象类,BufferedImage是其实现类,是一个带缓冲区图像类,主要作用是将一幅图片加载到内存中 * BufferedImage生成的图片在内存里有一个图像缓冲区,利用这个缓冲区我们可以很方便地操作这个图片 */
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
char[] rands = generCode();//产生随机的验证码
drawRands(graphics, rands);//产生图像
graphics.dispose();//结束图像的绘制过程,完成图像
/*将图像输出到客户端*/
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", byteArrayOutputStream);
byte[] buf = byteArrayOutputStream.toByteArray();
response.setContentLength(buf.length);
servletOutputStream.write(buf);
byteArrayOutputStream.close();
servletOutputStream.close();
session.setAttribute("checkcode", new String(rands));//将当前的验证码写入到session中
}
private char[] generCode() {
/*验证码的字符表*/
String chars = "0123456789";
char[] rands = new char[5];
for (int i = 0; i < 5; i++) {
int rand = (int) (Math.random()*10);
rands[i] = chars.charAt(rand);
}
/*rands = new char[]{49, 49, 49, 49, 49};*/
return rands;
}
private void drawRands(Graphics g, char[] rands) {
g.setColor(Color.WHITE);
g.setFont(new Font(null, Font.ITALIC|Font.BOLD, 18));
/*在不同高度上输出验证码的每个字符*/
g.drawString("" + rands[0], 0, 18);
g.drawString("" + rands[1], 14, 18);
g.drawString("" + rands[2], 28, 18);
g.drawString("" + rands[3], 42, 18);
g.drawString("" + rands[4], 56, 18);
CustomUtil.outPosition("green", "CheckCode.drawRands()");
CustomUtil.outParameter("green", "rands", String.valueOf(rands));
}
}
相关文件
今天的文章JavaWeb购物系统(课程设计)分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/26115.html