项目设计流程
业务流程
一个业务都是从后到前,首先第一步:设计数据库–dao–service(调用多个dao)–servlet(接受用户请求,做出响应)--------HTML(JSP技术)table-->model-->dao(jdbc)-->web-->servlet-->service
数据库创建
项目目录结构
实体类
UserModel
package com.situ.info.user.model;
public class UserModel {
private Integer id;
private String username;
private String pass;
private String sex;
private String hobby;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String string) {
this.username = string;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
private String address;
}
Dao
UserDao
package com.situ.info.user.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.situ.info.user.model.UserModel;
import com.situ.info.util.JDBCUtil;
public class UserDao {
public String insert(UserModel model) {
String sql="insert into user(username,pass,sex,hobby,address)values(?,?,?,?,?)";
Connection conn = null;// 建立连接,获得连接对象
PreparedStatement ps = null;// 定义状态集,一般使用预处理的状态集 PreparedStatement
String res="";
try {//异常处理推荐使用try catch
conn = JDBCUtil.getConnection();
ps = conn.prepareStatement(sql);// 获取状态集
ps.setString(1, model.getUsername());// 填充状态集数据
ps.setString(2, model.getPass());
ps.setString(3, model.getSex());
ps.setString(4, model.getHobby());
ps.setString(5, model.getAddress());
res+=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.close(conn, ps, null);
}
return res;//不能省略,前两 个return不一定返回
}
public String delete(UserModel model) {
String sql = "delete from student where username =?";
Connection conn = null;// 建立连接,获得连接对象
PreparedStatement ps = null;// 定义状态集,一般使用预处理的状态集 PreparedStatement
String res="";
try {
conn = JDBCUtil.getConnection();
ps = conn.prepareStatement(sql);// 获取状态集
ps.setString(1, model.getUsername());// 填充状态集数据
res+=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.close(conn, ps, null);
}
return res;
}
public String update(UserModel model) {
String sql="upsete student set username=?,pass=?,sex=?,hobby=?,address=? ";
Connection conn = null;// 建立连接,获得连接对象
PreparedStatement ps = null;// 定义状态集,一般使用预处理的状态集 PreparedStatement
String res="";
try {
conn = JDBCUtil.getConnection();
ps = conn.prepareStatement(sql);// 获取状态集
ps.setString(1, model.getUsername());// 填充状态集数据
ps.setString(2, model.getPass());
ps.setString(3, model.getSex());
ps.setString(4, model.getHobby());
ps.setString(5, model.getAddress());
res+=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.close(conn, ps, null);
}
return res;
}
public List<UserModel> selectList(UserModel model) {
StringBuffer sql=new StringBuffer("select id,username,pass,sex,hobby,address from user where 1=1");
//where 1=1方便拼接多个and
List<Object> list=new ArrayList<>();
String username=model.getUsername();
if(username != null && !username.isEmpty()) {//判断数据是否存在,---数据不是null或空字符串
sql.append(" and username=?");
list.add(username);
}
String pass=model.getPass();
if(pass != null && !pass.isEmpty()) {//判断数据是否存在,---数据不是null或空字符串
sql.append(" and pass=?");
list.add(pass);
}
Connection conn=null;// 建立连接
PreparedStatement ps = null; //定义状态集,一般使用预处理的状态集 PreparedStatement
ResultSet rs = null;//定义结果集
List<UserModel> result=new ArrayList<>();
try {
conn=JDBCUtil.getConnection1();// 获取状态集
ps = conn.prepareStatement(sql.toString());//stringbuffer类型转换成string类型
for(int i=0;i<list.size();i++)
ps.setObject(i+1, list.get(i));
rs = ps.executeQuery();//获取结果集
while(rs.next()) {
UserModel userModel=new UserModel();
userModel.setId(rs.getInt("id"));
userModel.setUsername(rs.getString("username"));
userModel.setPass(rs.getString("pass"));
userModel.setSex(rs.getString("sex"));
userModel.setHobby(rs.getString("hobby"));
userModel.setAddress(rs.getString("address"));
result.add(userModel);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.close(conn, ps, rs);
}
return result;
}
}
业务逻辑层
UserService
package com.situ.info.user.service;
import java.sql.SQLException;
import java.util.List;
import com.situ.info.user.dao.UserDao;
import com.situ.info.user.model.UserModel;
//业务逻辑层/服务层
public class UserService {//无具体业务逻辑实现
private UserDao dao=new UserDao();
/**
* 添加记录,username重复则不允许添加,返回null,否则可以添加,返回影响记录条数
* @param model
* @return String
*/
public String insert(UserModel model) {
UserModel m1=new UserModel();
m1.setUsername(model.getUsername());
List<UserModel> list = dao.selectList(m1);
if(list.isEmpty())
return dao.insert(model);
return null;
}
public String delete(UserModel model) {
return dao.delete(model);
}
public String update(UserModel model) {
return dao.update(model);
}
public List<UserModel> selectList(UserModel model) {
return dao.selectList(model);
}
/**
* 登录功能,账号存在其密码正确,成功登录
* @param model
* @return
*/
public UserModel login(UserModel model) {//登录功能,账号和密码
UserModel m1=new UserModel();
m1.setUsername(model.getUsername());
List<UserModel> list = dao.selectList(m1);
if(list.isEmpty()) {//账号不存在
m1.setId(-1);
return m1;
}
UserModel mdb = list.get(0);
if(list.get(0).getPass().equals(model.getPass()))//密码正确,登录成功
return mdb;
else {//登录成功
m1.setId(-2);
return m1;
}
}
}
控制层
UserServlet
package com.situ.info.user.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.situ.info.user.model.UserModel;
import com.situ.info.user.service.UserService;
import com.situ.info.util.MD5;
//控制层=接收请求+获取数据+封装对象+调用方法+页面跳转
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
private UserService service=new UserService();
// 把下一级对应文件对应的变量得到
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String message = null;
String path=null;
String back=null;
String contextPath=req.getContextPath();
String back1="<a href='"+contextPath+"/web/login.jsp'>返回登录</a>"
+ " <a href='"+contextPath+"/web/reg.jsp'>返回注册</a>";
String back2="<a href='"+contextPath+"/UserServlet?action=list'>返回列表</a>";
String path1="/web/success.jsp";
String path2="/UserServlet?action=list";
String path3="/web/list.jsp";
String action = req.getParameter("action");//得到隐藏域
switch (action) {//用switch分支和隐藏域完成多个请求请求到一个servlet
case "add":
message = add(req);
path=path1;
back=back2;
break;
case "reg":
message = add(req);
path=path1;
back=back1;
break;
case "login":
message=login(req);
if("登陆成功".equals(message)) {
path=path2;
}else {
path=path1;
back=back1;
}
break;
case "list":
UserModel userModel=new UserModel();
req.setAttribute("list", service.selectList(userModel));
path=path3;
break;
default:
break;
}
req.setAttribute("back", back);
req.setAttribute("message", message);
req.getRequestDispatcher(path).forward(req, resp);
}
private String login(HttpServletRequest req) {//登录成功-用户信息-存到session中
String username =req.getParameter("username");
if(username==null||username.isEmpty())//账号为空检验
return "操作失败,账号不能为空";
String pass =req.getParameter("pass");
if(pass==null||pass.isEmpty())//密码为空检验
return "操作失败,密码不能为空";
if(!isOKAnthcode(req))//验证码检验
return "操作失败,验证码错误";
pass=MD5.encode(pass);
UserModel model = new UserModel();
model.setUsername(username);
model.setPass(pass);
UserModel mdb = service.login(model);
Integer id=mdb.getId();
if(id==-1) {
return "账号不存在";
}
if(id==-2) {
return "密码错误";
}
req.getSession().setAttribute("user", mdb);
return "登陆成功";
}
private boolean isOKAnthcode(HttpServletRequest req) {
String authcode = req.getParameter("authcode");//取出网页传过来的的验证码
Object auth_code = req.getSession().getAttribute("auth_code");//得到session中存的验证码
return auth_code.toString().equals(authcode);
}
private String add(HttpServletRequest req) {//往数据库中添加数据,用户注册
String username =req.getParameter("username");
if(username==null||username.isEmpty())//账号为空检验
return "操作失败,账号不能为空";
String pass =req.getParameter("pass");
if(pass==null||pass.isEmpty())//密码为空检验
return "操作失败,密码不能为空";
if(!isOKAnthcode(req))
return "操作失败,验证码错误";
pass=MD5.encode(pass);
String sex =req.getParameter("sex");
String[] hobby =req.getParameterValues("hobby");
StringBuffer hobbystring=new StringBuffer();
if(hobby!=null&&hobby.length>0) {//判断不为空或空字符串
hobbystring.append(hobby[0]);
for(int i=0;i<hobby.length;i++)//拼接字符串
hobbystring.append(",").append(hobby[i]);
}
String address =req.getParameter("address");
UserModel model=new UserModel();
model.setUsername(username);
model.setPass(pass);
model.setSex(sex);
model.setHobby(hobbystring.toString());
model.setAddress(address);
String result = service.insert(model);
if(result!=null&&!result.isEmpty()) {
return "操作成功,账号:"+username;
}else
return "操作失败,账号重复";
}
}
AuthCodeServlet
package com.situ.info.user.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
//awt swing java可视化界面的工具
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AuthCodeServlet")
public class AuthCodeServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static char[] chs="1234567890abcdefghijklmnopqrstuiwxyz".toCharArray();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BufferedImage image=new BufferedImage(75,25,BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(new Color(200,200,255));
g.fillRect(0, 0, 75, 75);
g.setFont(new Font("隶书", Font.BOLD, 15));
StringBuffer str = new StringBuffer();
Random r = new Random();
for(int i=0;i<4;i++) {
int index=r.nextInt(10);
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.drawString(chs[index]+"",15*i+3, 16+(r.nextInt(3)));
str.append(chs[index]);
}
req.getSession().setAttribute("auth_code", str.toString());//用Session可以在多变量的情况下使用
ImageIO.write(image, "jpg", resp.getOutputStream());//以字节流的形式返回到网页上
}
}
前端页面
reg注册
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- http://127.0.0.1:8080/demo220107/web/reg.jsp -->
<!-- <form action="/demo220107/UserServlet"> -->
<%-- <form action="<%=request.getContextPath() %>/UserServlet"> --%>
<form action="${pageContext.request.contextPath }/UserServlet" method="post">
账号<input type="text" name="username" /><br>
密码<input type="password" name="pass" /><br>
性别<input type="radio" name="sex" value="男" />男
<input type="radio" name="sex" value="女" />女<br>
爱好<input type="checkbox" name="hobby" value="跑步" />跑步
<input type="checkbox" name="hobby" value="游泳"/>游泳
<input type="checkbox" name="hobby" value="睡觉"/>睡觉
地址<select name="address">
<option value="北京">北京</option>
<option value="山东">山东</option>
<option value="上海">上海</option>
</select><br>
<img src="${pageContext.request.contextPath }/AuthCodeServlet"
onclick="this.src='${pageContext.request.contextPath }/AuthCodeServlet?'+Math.random()">
<input type="text" name="authcode"><br>
<input type="reset">
<input type="submit" value="注册">
<!-- 实现页面跳转 -->
<input type="button" value="跳转登录" onclick="toLogin()">
<!-- 让多个请求请求到同一个servlet,用隐藏域实现 -->
<input type="hidden" name="action" value="reg">
</form>
<script type="text/javascript">
function toLogin() {
location.href="${pageContext.request.contextPath}/web/login.jsp";//实现页面跳转功能
}
</script>
</body>
</html>
login登录界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- http://127.0.0.1:8080/demo220107/web/login.jsp -->
<form action="${pageContext.request.contextPath }/UserServlet">
账号<input type="text" name="username" /><br>
密码<input type="password" name="pass" /><br>
<img src="${pageContext.request.contextPath }/AuthCodeServlet"
onclick="this.src='${pageContext.request.contextPath }/AuthCodeServlet?'+Math.random()">
<input type="text" name="authcode"><br>
<input type="reset">
<input type="submit" value="登录">
<!-- 实现页面跳转 -->
<input type="button" value="注册" onclick="toReg()">
<!-- 让多个请求请求到同一个servlet,用隐藏域实现 -->
<input type="hidden" name="action" value="login">
</form>
<script type="text/javascript">
function toReg() {
location.href="${pageContext.request.contextPath}/web/reg.jsp";//实现页面跳转功能
}
</script>
</body>
</html>
success注册成功界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${message}<br>
<c:out value="${back }" escapeXml="false" />
<%-- <a href="${pageContext.request.contextPath}/web/login.jsp">返回登录</a> --%>
<%-- <a href="${pageContext.request.contextPath}/web/reg.jsp">返回注册</a> --%>
</body>
</html>
list列表界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
列表
<form action="">
账号:<input type="text" name="user">
<input type="submit" value="查询">
<input type="button" value="添加" onclick="toAdd()">
</form><br>
<table style="border: 1px solid black;width:90%">
<thead>
<tr>
<td>序号</td><td>账号</td><td>性别</td>
<td>爱好</td><td>地址</td><td>操作</td>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="l" varStatus="k">
<tr>
<td>${k.count }</td>
<td>${l.username }</td>
<td>${l.sex }</td>
<td>${l.hobby }</td>
<td>${l.address }</td>
<td>
<a href="">修改</a>
<button onclick="">删除</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<script type="text/javascript">
var contextPath="${pageContext.request.contextPath}";
function toAdd() {
location.href=contextPath+"/web/add.jsp"
}
</script>
</body>
</html>
add添加界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/UserServlet" method="post">
账号<input type="text" name="username" /><br>
密码<input type="password" name="pass" /><br>
性别<input type="radio" name="sex" value="男" />男
<input type="radio" name="sex" value="女" />女<br>
爱好<input type="checkbox" name="hobby" value="跑步" />跑步
<input type="checkbox" name="hobby" value="游泳"/>游泳
<input type="checkbox" name="hobby" value="睡觉"/>睡觉
地址<select name="address">
<option value="北京">北京</option>
<option value="山东">山东</option>
<option value="上海">上海</option>
</select><br>
<img src="${pageContext.request.contextPath }/AuthCodeServlet"
onclick="this.src='${pageContext.request.contextPath }/AuthCodeServlet?'+Math.random()">
<input type="text" name="authcode"><br>
<input type="reset">
<input type="submit" value="添加">
<!-- 实现页面跳转 -->
<input type="button" value="返回列表" onclick="toList()">
<!-- 让多个请求请求到同一个servlet,用隐藏域实现 -->
<input type="hidden" name="action" value="add">
</form>
<script type="text/javascript">
function toList() {
location.href="${pageContext.request.contextPath}/UserServlet?action=list";//实现页面跳转功能
}
</script>
</body>
</html>