0%

java之jsp

说明

  • 上篇主要搭建了servlet,本次主要加入jsp的应用,功能包括增删改查
  • 本次java 版本
1
2
3
4
C:\Users\Administrator>java -version
java version "1.8.0_381"
Java(TM) SE Runtime Environment (build 1.8.0_381-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.381-b09, mixed mode)

简单实例

  • webapp下新增index.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<%
String user=(String)session.getAttribute("user");
if (user != null) {
// 用户已登录
out.println("<a href=\"homePage.jsp\">");
out.println("登录成功主页");
out.println("</a>");
} else {
// 用户未登录
out.println("<a href=\"login.jsp\">");
out.println("登录界面");
out.println("</a>");
}
%>
</body>
</html>
  • 当sesssion数据不存在,可点击进入登录界面

image-20231201173302810

  • webapp/login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<form action="login" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
  • 登录的servlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package xyz.shi.servlet;
...
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;

@WebServlet("/login")
public class LoginServlet extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");

// 验证用户名和密码
if (username.equals("admin") && password.equals("123456")) {
// 登录成功,创建会话
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("homePage.jsp");
} else {
// 登录失败,返回登录页面
request.setAttribute("error", "用户名或密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
  • webapp/homePage.jsp
1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<h1>欢迎登录,${username}!</h1>
<a href="logout">注销</a>
</body>
</html>
  • 注销的Servlet
1
2
3
4
5
6
7
8
9
10
11
package xyz.shi.servlet;

...
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect("login.jsp");
}
}

image-20231201173645669

结合jdbc

  • 基础知识参考这篇文章

  • 首先pom.xml中加入本次需要的依赖文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

jstl主要是在jsp中使用的标签语法

三层架构

  • 表示层:主要是指与用户交互的界面。用于接收用户输入的数据和显示处理后用户需要的数 据。

  • 业务逻辑层:UI层(表示)和DAL层(数据访问)之间的桥梁。实现业务逻辑。业务逻辑具体包含:验证、计算、业务规则等等。

  • 数据访问层:与数据库打交道。主要实现对数据的增、删、改、查。将存储在数据库中的数据提交给业务层,同时将业务层处理的数据保存到数据库。

  • 实体层:它不属于三层中的任何一层,贯穿于三层,在三层之间传递数据;

实体层

  • xyz.shi.entity.User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package xyz.shi.entity;
public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
// 因为QueryRunner创建Bean对象的过程使用的是newInstance()方法,该方法只能调用无参构
public User () {

}
public User(int id,String name, String password) {
this.name = name;
this.id = id;
this.password = password;
}
public void setId(int id) { this.id = id;}
public String getName() { return name;}
public void setName(String name) { this.name = name;}
public void setPassword(String password) {this.password = password;}
public String getPassword() {return password;}

}

数据访问层

  • 分为接口和实现接口,代码放在xyz.shi.dao 包下

  • 接口层xyz.shi.dao.UserDao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package xyz.shi.dao;

import xyz.shi.entity.User;

import java.sql.SQLException;
import java.util.List;

public interface UserDao {
//返回所有对象
List<User> queryAllList(String sql);
// 查找多条记录
List<User> queryList(String sql,Object ...params);
// 查找一条记录
User queryOne(String sql, Object... parameters);
// 修改(删除)一条记录
int update(String sql, Object... parameters) ;
}

  • 实现接口层xyz.shi.dao.impl.UserDaoImpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package xyz.shi.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import xyz.shi.dao.UserDao;
import xyz.shi.entity.User;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import xyz.shi.util.jdbcUtil;
public class UserDaoImpl implements UserDao {
private QueryRunner qr = new QueryRunner();
// 返回所有对象
@Override
public List<User> queryAllList(String sql) {
Connection connection = null;
try {
connection =jdbcUtil.getConnection();
return qr.query(connection, sql, new BeanListHandler<User>(User.class));
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
jdbcUtil.closeResource(null,null, connection);
}
}
// 返回多个对象(即查询的结果是多行)
@Override
public List<User> queryList(String sql, Object... params) {
Connection connection = null;
try {
connection =jdbcUtil.getConnection();
return qr.query(connection, sql, new BeanListHandler<User>(User.class), params);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
jdbcUtil.closeResource(null,null, connection);
}
}
// 查询单行结果
@Override
public User queryOne(String sql, Object... parameters) {
Connection connection = null;

try {
connection =jdbcUtil.getConnection();
return qr.query(connection, sql, new BeanHandler<User>(User.class), parameters);

} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
jdbcUtil.closeResource(null,null, connection);
}

}
// 修改(增删改通用)
@Override
public int update(String sql, Object... parameters) {
Connection connection = null;
try {
connection =jdbcUtil.getConnection();
return qr.update(connection,sql,parameters);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
jdbcUtil.closeResource(null,null, connection);
}
}
}

业务逻辑层

  • 分为接口和实现接口,代码放在xyz.shi.service 包下

  • 接口层xyz.shi.service.UserService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package xyz.shi.service;
import xyz.shi.entity.User;
import java.util.List;
public interface UserService {
//根据userId查询一个user
User getUser(String id);
//根据name和password查询一个user
Boolean ableLogin (String name , String password);
//查找多条user对象
List<User> getUserList(Object... parameters);
//查找所有user对象
List<User> getAllUser();
//增加一个user
int addUser(Object... parameters);
//删除一个user
int deleteUser(int userId);
//修改一个user的信息
int updateUser(Object... parameters);
}

  • xyz.shi.service.impl.UserServiceImpl 实现接口,这里就是编写具体的逻辑
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package xyz.shi.service.impl;

import xyz.shi.dao.UserDao;
import xyz.shi.dao.impl.UserDaoImpl;
import xyz.shi.entity.User;
import xyz.shi.service.UserService;

import java.sql.SQLException;
import java.util.List;

public class UserServiceImpl implements UserService {
//创建UserDaoImpl对象
private UserDao userDao = new UserDaoImpl();
//查询所有
@Override
public List<User> getAllUser() {
String sql ="select * from `users`";
try {
return userDao.queryAllList(sql);
} catch (Exception e) {
System.out.println(e);
return null;
}
}
//根据userId查询一个user
@Override
public User getUser(String userId) {
String sql = "select * from `users` where id = ? ";
try {
return userDao.queryOne(sql,userId);
} catch (Exception e) {
System.out.println(e);
return null;
}
}
//根据userId和password查询一个user
@Override
public Boolean ableLogin (String name , String password) {
String sql ="select * from `users` where name = ? and password = ? ";
User user = userDao.queryOne(sql, name, password);

return user != null ? true : false;

}
//根据条件查询多个user
@Override
public List<User> getUserList(Object... parameters) {
String sql ="select * from `users` where ? = ? ";
try {
return userDao.queryList(sql,parameters);
} catch (Exception e) {
System.out.println(e);
return null;
}
}
//增加一个user
@Override
public int addUser(Object... parameters) {
String sql ="insert into `users` (name, password) values (?, ?)";
return userDao.update(sql, parameters);
}
//删除一个user
@Override
public int deleteUser(int userId) {
String sql ="delete from `users` where id = ? ";
return userDao.update(sql,userId);
}
//修改一个user的信息
@Override
public int updateUser(Object... parameters) {
String sql ="update `users` set name = ?,password = ? where id = ? ";
return userDao.update(sql,parameters);
}

}

表示层

  • 也就是用户界面层

  • xyz.shi.servlet 层,主要放jsp文件传过来的数据,然后把服务器数据传给jsp页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package xyz.shi.servlet;

import xyz.shi.entity.User;
import xyz.shi.service.UserService;
import xyz.shi.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;

@WebServlet("/login")
public class LoginServlet extends HttpServlet{
// 注意这里get的写法,当其他页面新增或者修改成功后,跳转到/login页面,然后自动读取用户列表数据
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String session = (String) req.getSession().getAttribute("username");
if (session != null) {
UserService userService = new UserServiceImpl();
List<User> users = userService.getAllUser();
req.setAttribute("userList", users);
req.getRequestDispatcher("homePage.jsp").forward(req, resp);;

}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserService userService = new UserServiceImpl();
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean login = userService.ableLogin(username, password);
// 验证用户名和密码
if (login) {
// 登录成功,创建会话
HttpSession session = request.getSession();
List<User> users = userService.getAllUser();
request.setAttribute("userList", users);

session.setAttribute("username", username);
System.out.println("登录成功");
request.getRequestDispatcher("homePage.jsp").forward(request, response);;
} else {
// 登录失败,返回登录页面
System.out.println("登录失败");
request.setAttribute("error", "用户名或密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);

}
}
}
  • 默认打开的是index.jsp界面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<%
String user=(String)session.getAttribute("username");
if (user != null) {
// 用户已登录
out.println("<a href=\"homePage.jsp\">");
out.println("登录成功主页");
out.println("</a>");
} else {
// 用户未登录
out.println("<a href=\"login.jsp\">");
out.println("登录界面");
out.println("</a>");
}
%>
</body>
</html>
  • 登录界面login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<form action="login" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
  • 登录后的界面homepage.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><!DOCTYPE html>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<h1>欢迎登录,${username}!</h1>
<a href="add.jsp">添加</a>
<table>
<tr>
<td>id</td>
<td>用户名</td>
<td>状态</td>
<td>操作</td>
</tr>
<c:forEach var="item" items="${requestScope.userList}">
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td><a href="userFind?id=${item.id}">修改</a>
<td><a href="<%=request.getContextPath()%>/userDel?id=${item.id}">删 除</a></td>
</tr>
</c:forEach>

</table>
<a href="logout">注销</a>
</body>
</html>

登录成功后LoginServlet把用户列表传给了homePage.jsp,后续的修改,删除逻辑也是一样

servlet层

  • 比如下面这是修改用户名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package xyz.shi.servlet;

import xyz.shi.entity.User;
import xyz.shi.service.UserService;
import xyz.shi.service.impl.UserServiceImpl;
import xyz.shi.utils.GetUsersUtils;

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 java.io.IOException;
import java.util.List;

@WebServlet("/userUpdate")
public class UpdateUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserService userService = new UserServiceImpl();
int userId = Integer.parseInt(request.getParameter("id"));
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User(userId, username, password);
int flag = userService.modify(user);
if (flag > 0) {
System.out.println("修改数据成功");
GetUsersUtils.GetUsers(request, response);
} else {
// 登录失败,返回登录页面
System.out.println("修改数据失败");
request.setAttribute("message", "failed");

}
}
}