使用Servlet+JSP实现学生管理系统
eg1: 使用servlet来实现登录功能
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录页面</h1>
<!--前端访问后台资源 不加/-->
<form action="login" method="post">
用户名: <input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
爱好: <input type="checkbox" name="love" value="1">学习
<input type="checkbox" name="love" value="2">篮球
<input type="checkbox" name="love" value="3">游戏<br/>
<input type="submit" value="登录">
</form>
</body>
</html>
LoginServlet:
package com.jishou.servlet;
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;
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post请求。。。。。");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get请求。。。。");
}
}
登录逻辑里面取前台用户输入的参数:
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//登录的处理逻辑
//1. 取前台表单的参数 request
/*
public String getParameter(String name) 返回指定name对应的参数的值
public String[] getParameterValues(String name) 返回指定name对应的一组参数值,返回值是数组
public Enumeration getParameterNames() 返回所有客户请求的参数名
*/
//2. 登录处理
//参数名必须和前台表单name属性值一致
request.setCharacterEncoding("utf-8");//设置请求编码 放在第一行
String username = request.getParameter("username");//取用户名
String password = request.getParameter("password");//取密码
String[] loves = request.getParameterValues("love");//取爱好
System.out.println("用户名: "+username+" 密码:"+password);
if(loves!=null&&loves.length>0){
for(String love: loves){
System.out.println("爱好: "+love);
}
}
//3. 产生响应 成功或者失败
//通过response响应对象输出内容到浏览器里面
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");//说明以html方式来响应
PrintWriter out = response.getWriter();//获取字符输出流
out.println("用户名是:"+username+"密码是: "+password);
out.flush();//刷新流
out.close();//关闭流
}
}
url访问:
http://localhost:8080/servlet02_2_war_exploded/login.html
eg2: 使用servlet来实现登录功能
1.创建数据库表 mysql
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B1XWDjyA-1638964004199)(img\user.png)]
2.创建web project
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bcr8v8cE-1638964004202)(img\stuManage.png)]
3. 在web目录下创建登录页面 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录页面</h1>
<!--前端访问后台资源 不加/-->
<form action="login" method="post">
用户名: <input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
4.编写实体类User
package com.jishou.pojo;
public class User {
private int id;
private String username;
private String password;
public User() {
}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
5.编写数据访问层 UserDao接口 和 接口实现类
导入mysql依赖,复制到web–web-inf下的lib目录底下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pXGutDHk-1638964004204)(img\mysql.png)]
注意: web项目中mysql依赖包必须复制到web-inf下面的lib目录里面
吧mysql依赖引入到该工程里面
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z7smX22l-1638964004205)(img\yilai1.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s4Sqo6zS-1638964004207)(img\yilai2.png)]
数据库连接工具类 DBUtil
package com.jishou.util;
import java.sql.*;
public class DBUtil {
private static String driverClassName="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf8";
private static String username="root";
private static String password="123456";
static{
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs){
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
public static void close(Connection conn, PreparedStatement pstmt){
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
UserDao
package com.jishou.dao;
import com.jishou.pojo.User;
public interface UserDao {
public User queryOneUser(User user) ;
public int insertUser(User user);
}
UserDaoImpl
package com.jishou.dao;
import com.jishou.pojo.User;
import com.jishou.util.DBUtil;
import java.sql.*;
public class UserDaoImpl implements UserDao{
/*@Override
public User queryOneUser(User user) throws SQLException, ClassNotFoundException {
//1.加载驱动 建厂
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc://mysql:localhost:3306/test?characterEncoding=utf8";
String username="root";
String password="123456";
String sql="select * from user where username=? and password=?";
User u=null;
Class.forName(driverClassName);
//2.获取连接 修路
Connection conn = DriverManager.getConnection(url, username, password);
//3.创建PreparedStatement 造车
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,user.getUsername());
pstmt.setString(2,user.getPassword());
//4.执行操作 拉货
ResultSet rs = pstmt.executeQuery();
//5.处理结果集 查询会有结果集 增删改 没有 处理货物
if(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
u=new User(id,name,pass);
}
//6. 关闭资源 路 砸了 货物 毁了 车 砸了
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
return u;
}*/
public User queryOneUser(User user) {
//1.加载驱动 建厂
String sql="select * from user where username=? and password=?";
User u=null;
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
//2.获取连接 修路
conn= DBUtil.getConnection();
//3.创建PreparedStatement 造车
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
//4.执行操作 拉货
rs = pstmt.executeQuery();
//5.处理结果集 查询会有结果集 增删改 没有 处理货物
if (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
u = new User(id, name, pass);
}
}catch (SQLException e){
e.printStackTrace();
}
//6. 关闭资源 路 砸了 货物 毁了 车 砸了
DBUtil.close(conn,pstmt,rs);
return u;
}
@Override
public int insertUser(User user) {
return 0;
}
}
6.编写service层接口和实现类
UserService
package com.jishou.service;
import com.jishou.pojo.User;
public interface UserService {
//登录
public User login(User user);
//注册
public boolean register(User user);
}
UserServiceImpl
package com.jishou.service;
import com.jishou.dao.UserDao;
import com.jishou.dao.UserDaoImpl;
import com.jishou.pojo.User;
public class UserServiceImpl implements UserService{
private UserDao userDao=new UserDaoImpl();
@Override
public User login(User user) {
return userDao.queryOneUser(user);
}
@Override
public boolean register(User user) {
return false;
}
}
7.编写Servlet的登录实现逻辑
LoginServlet
package com.jishou.servlet;
import com.jishou.pojo.User;
import com.jishou.service.UserService;
import com.jishou.service.UserServiceImpl;
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.io.PrintWriter;
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 取参数
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User qtUser=new User(username,password);
//连数据库查询
User htUser = userService.login(qtUser);
//响应
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//判断是否登录成功
if(htUser!=null){
out.println("<h1>登录成功</h1>");
}else{
out.println("<h1>登录失败</h1>");
}
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
8.浏览器url访问登录页面,展示运行效果
http://localhost:8080/stuManage_02_war_exploded/login.html
正常jdbc流程:
public User queryOneUser(User user) throws SQLException, ClassNotFoundException {
//1.加载驱动 建厂
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc://mysql:localhost:3306/test?characterEncoding=utf8";
String username="root";
String password="123456";
String sql="select * from user where username=? and password=?";
User u=null;
Class.forName(driverClassName);
//2.获取连接 修路
Connection conn = DriverManager.getConnection(url, username, password);
//3.创建PreparedStatement 造车
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,user.getUsername());
pstmt.setString(2,user.getPassword());
//4.执行操作 拉货
ResultSet rs = pstmt.executeQuery();
//5.处理结果集 查询会有结果集 增删改 没有 处理货物
if(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String pass = rs.getString(3);
u=new User(id,name,pass);
}
//6. 关闭资源 路 砸了 货物 毁了 车 砸了
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
return u;
}
eg3: 使用Servlet实现注册功能
-
在web目录下新建register.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>注册页面</h1> <!--前端访问路径都不加/ --> <form action="register" method="post"> 用户名: <input type="text" name="username"><br> 密码: <input type="password" name="password"><br> <input type="submit" value="注册"> </form> </body> </html>
-
编写数据访问层UserDao和实现类里面的注册逻辑
UserDao接口
public int insertUser(User user);
UserDaoImpl接口实现类
@Override public int insertUser(User user) { String sql="INSERT INTO user (username, password) VALUES ( ?, ?)"; Connection conn = DBUtil.getConnection(); PreparedStatement pstmt=null; int row=0; try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); row = pstmt.executeUpdate(); }catch(SQLException e) { e.printStackTrace(); }finally { DBUtil.close(pstmt,conn); } return row; }
-
编写service层注册逻辑
UserService接口:
public boolean register(User user);//注册
UserServiceImpl接口实现类
@Override public boolean register(User user) { int row = userDao.insertUser(user); if(row>0){ return true; } return false; }
-
编写RegisterServlet注册实现逻辑
RegisterServlet
package com.jishou.servlet; import com.jishou.pojo.User; import com.jishou.service.UserService; import com.jishou.service.UserServiceImpl; 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.io.PrintWriter; @WebServlet(name = "RegisterServlet",urlPatterns = "/register") public class RegisterServlet extends HttpServlet { private UserService userService=new UserServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取参 req.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); User qtUser=new User(username,password); //链接数据库添加 boolean flag = userService.register(qtUser); /*resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); //响应 if(flag){ out.println("<h1>注册成功<h1>"); }else { out.println("<h1>注册失败<h1>"); } out.flush(); out.close();*/ //注册成功 需要跳转到登录页面,注册失败 需要 回到注册页面,继续注册 if(flag){ //重定向 就表示重新定位到一个地址 resp.sendRedirect("login.html"); }else{ resp.sendRedirect("register.html"); } } }
-
浏览器url访问测试,展示运行效果
http://localhost:8080/stuManage_04_war_exploded/register.html
eg4: 使用Servlet实现查询所有学生信息功能
-
创建数据库表
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cVN6h43P-1638964004208)(img\stu.png)]
-
编写实体类
Student
package com.jishou.pojo; import java.util.Date; public class Student { private Integer id; private String name; private Date birthday; private Integer age; private String address; private String photo; public Student() { } public Student(Integer id, String name, Date birthday, Integer age, String address, String photo) { this.id = id; this.name = name; this.birthday = birthday; this.age = age; this.address = address; this.photo = photo; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", birthday=" + birthday + ", age=" + age + ", address='" + address + '\'' + ", photo='" + photo + '\'' + '}'; } }
-
数据访问层StudentDao,StudentDaoImpl查询所有
StudentDao
package com.jishou.dao; import com.jishou.pojo.Student; import java.util.List; public interface StudentDao { public List<Student> queryAllStudents(); }
StudentDaoImpl
package com.jishou.dao; import com.jishou.pojo.Student; import com.jishou.util.DBUtil; import java.sql.*; import java.util.ArrayList; import java.util.List; public class StudentDaoImpl implements StudentDao{ @Override public List<Student> queryAllStudents() { String sql="select * from stu"; PreparedStatement pstmt=null; ResultSet rs=null; List<Student> list=new ArrayList<>(); //2. 获取连接 修路 Connection conn = DBUtil.getConnection(); try { //3. 创建PreparedStatement 造车 pstmt = conn.prepareStatement(sql); //4. 执行sql 拉货 rs = pstmt.executeQuery(); //5. 处理结果集 查询会有结果集 处理货物 while (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); Date birthday = rs.getDate(3); int age = rs.getInt(4); String address = rs.getString(5); String photo = rs.getString(6); Student student=new Student(id,name,birthday,age,address,photo); list.add(student); } }catch (SQLException e){ e.printStackTrace(); }finally { //6. 关闭资源 货 车 路全都毁了 DBUtil.close(rs,pstmt,conn); } return list; } }
-
服务层service层接口和实现
StudentService
package com.jishou.service; import com.jishou.pojo.Student; import java.util.List; public interface StudentService { public List<Student> queryAllStudents(); }
StudentServiceImpl
package com.jishou.service; import com.jishou.dao.StudentDao; import com.jishou.dao.StudentDaoImpl; import com.jishou.pojo.Student; import java.util.List; public class StudentServiceImpl implements StudentService{ private StudentDao studentDao=new StudentDaoImpl(); @Override public List<Student> queryAllStudents() { return studentDao.queryAllStudents(); } }
-
查询所有的Servlet实现
ListServlet
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; 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.net.ServerSocket; import java.util.List; @WebServlet(name = "ListServlet",urlPatterns = "/list") public class ListServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //查询所有学生 List<Student> list = studentService.queryAllStudents(); //吧学生信息放在request对象里面 req.setAttribute("list",list); //请求转发 req.getRequestDispatcher("list.jsp").forward(req,resp); } }
-
前端页面
list.jsp
<%@ page import="com.jishou.pojo.Student" %> <%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h1>学生管理系统</h1> <table> <tr> <td>编号</td> <td>姓名</td> <td>出生日期</td> <td>年龄</td> <td>地址</td> <td><a href="">添加学生</a></td> </tr> <c:forEach var="s" items="${requestScope.list}"> <tr> <td>${s.id}</td> <td>${s.name}</td> <td>${s.birthday}</td> <td>${s.age}</td> <td>${s.address}</td> <td> <a href="">修改</a> <a href="">删除</a> </td> </tr> </c:forEach> </table> </body> </html>
-
浏览器url访问
http://localhost:8080/stuManage_04_war_exploded/list
eg5: 实现在首页展示当前用户名功能,退出系统功能,展示当前服务器总在线人数功能
LoginServlet:
package com.jishou.servlet;
import com.jishou.pojo.User;
import com.jishou.service.UserService;
import com.jishou.service.UserServiceImpl;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
private Integer count=0;//总在线人数
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 取前台参数
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User qtuser=new User(username,password);
//2. 连接数据库查询
User htuser = userService.login(qtuser);
//3. 判断登录是否成功
if(htuser!=null){
//登录成功
HttpSession session = request.getSession();
ServletContext servletContext = request.getServletContext();
session.setAttribute("user",htuser);
servletContext.setAttribute("count",++count);
response.sendRedirect("list");
}else{
//登录失败
response.sendRedirect("login.html");
}
}
}
LogOutServlet:
package com.jishou.servlet;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name = "LogOutServlet",urlPatterns = "/logout")
public class LogOutServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.invalidate();//session失效
//让总在线人数减少
ServletContext servletContext = req.getServletContext();
Integer count = (Integer) servletContext.getAttribute("count");
servletContext.setAttribute("count",--count);
resp.sendRedirect("login.html");
}
}
list.jsp
加上下面代码:
<%
List<Student> list = (List<Student>) request.getAttribute("list");
User user = (User) request.getSession().getAttribute("user");
%>
<div id="login">欢迎<%=user.getUsername()%>登录 <a href="logout">退出系统</a></div>
<div id="count">当前共有<%=application.getAttribute("count")%>人在线</div>
eg6: 使用Servlet实现添加、删除和修改学生信息功能
思路:
添加:
<a href="add.jsp">添加学生</a>
当在主页面点击添加超链接时--->跳转到add.jsp----->add.jsp表单里面输入相应值时,跳转AddServlet,实现添加逻辑
----->AddServlet实现添加功能------>添加成功,跳转到ListServlet,添加失败,回到添加页面add.jsp
注意: 数据库表主键id自增,所以不用添加id属性
删除:
<a href="delete?id=<%=s.getId()%>">删除</a>
删除要根据id来删除该条数据信息;当点击删除超链接时,需要跳转到DeleteServlet,并吧要删除的id传过去,删除成功,再重新查询所有
超链接访问属于get请求方式,get请求走浏览器地址栏传参,所以href="delete?id=<%=s.getId()%>" 即可
修改:
修改的实现逻辑是在update.jsp里面在原来老数据的基础之上吧老数据修改成新数据,所以,修改的逻辑需要先根据id来查询单个,查询出来的对象信息回显到update.jsp表单里面,用户再在老数据的基础之上输入新数据,点击修改按钮,实现后台的修改功能;修改成功,回到主页面,查询所有;修改失败,回到update.jsp
list.jsp <a href="load?id=<%=s.getId()%>">修改</a> ----->LoadServlet 根据id查询单个---->
update.jsp 实现老数据回显------>用户在老数据的基础之上吧老数据修改成新数据,submit修改按钮----->
UpdateServlet 修改的后台实现----->修改成功,ListServlet;修改失败,回到update.jsp
注意: 由于数据库中birthday是date类型,他对应的java代码中的类型为java.sql.Date; 而平时java代码使用最多的是java.util.Date.
所以就涉及到不同的日期类型之间的转换,最好的方式就是写个日期工具类DateUtil:
DateUtil:
package com.jishou.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
// util.date转换成sql.date
public static java.sql.Date toSqlDate(Date date){
return new java.sql.Date(date.getTime());
}
// sql.date转换成util.date
public static Date toUtilDate(java.sql.Date date){
return new java.util.Date(date.getTime());
}
//String 转换成发 util.Date
public static Date strToUtilDate(String dateStr){
Date date = null;
//注意format的格式要与日期String的格式相匹配
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
//util.Date转换为String
public static String dateToStr(Date date){
String dateStr = "";
//format的格式可以任意
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
dateStr = sdf.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return dateStr;
}
}
添加功能:
- 前台:add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<center>
<h1>添加学生</h1>
<form action="add" method="post">
<table width="50%" height="35%">
<tr>
<td>姓名</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>生日</td>
<td><input type="date" name="birthday"></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td>头像</td>
<td><input type="text" name="photo"></td>
</tr>
<tr>
<td><input type="submit" value="添加"></td>
<td><input type="reset" name="重置"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
-
后台:dao层:
StudentDao:
package com.jishou.dao;
import com.jishou.pojo.Student;
import java.util.List;
public interface StudentDao {
public List<Student> queryAllStudents();
public int addStudent(Student student);
public int deleteStudentById(Integer id);
public int updateStudent(Student student);
public Student queryOneStudentById(Integer id);
}
StudentDaoImpl:
package com.jishou.dao;
import com.jishou.pojo.Student;
import com.jishou.util.DBUtil;
import com.jishou.util.DateUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao{
@Override
public List<Student> queryAllStudents() {
String sql="select * from stu";
Connection conn = DBUtil.getConnection();
List<Student> list = new ArrayList<>();
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
pstmt= conn.prepareStatement(sql);
rs= pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
String sname = rs.getString(2);
int age = rs.getInt(3);
Date birthday = rs.getDate(4);
String address = rs.getString(5);
String photo = rs.getString(6);
Student student = new Student(id, sname, age, birthday, address, photo);
list.add(student);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(rs,pstmt,conn);
}
return list;
}
@Override
public int addStudent(Student student) {
String sql="INSERT INTO stu ( `sname`, `age`, `birthday`, `address`, `photo`) VALUES (?, ?, ?,?,?)";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
int row=0;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,student.getSname());
pstmt.setInt(2,student.getAge());
pstmt.setDate(3, DateUtil.toSqlDate(student.getBirthday()));
pstmt.setString(4,student.getAddress());
pstmt.setString(5,student.getPhoto());
row= pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(pstmt,conn);
}
return row;
}
@Override
public int deleteStudentById(Integer id) {
String sql="delete from stu where id=?";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
int row=0;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setInt(1,id);
row= pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(pstmt,conn);
}
return row;
}
@Override
public int updateStudent(Student student) {
String sql="UPDATE stu SET `sname`=?, `age`=?, `birthday`=?, `address`=?, `photo`=? WHERE `id`=?";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
int row=0;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,student.getSname());
pstmt.setInt(2,student.getAge());
pstmt.setDate(3, DateUtil.toSqlDate(student.getBirthday()));
pstmt.setString(4,student.getAddress());
pstmt.setString(5,student.getPhoto());
pstmt.setInt(6,student.getId());
row= pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(pstmt,conn);
}
return row;
}
@Override
public Student queryOneStudentById(Integer id) {
String sql="select * from stu where id=?";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
ResultSet rs=null;
Student student=null;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setInt(1,id);
rs= pstmt.executeQuery();
if (rs.next()) {
int idd = rs.getInt(1);
String sname = rs.getString(2);
int age = rs.getInt(3);
Date birthday = rs.getDate(4);
String address = rs.getString(5);
String photo = rs.getString(6);
student = new Student(idd, sname, age, birthday, address, photo);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(rs,pstmt,conn);
}
return student;
}
}
- service层:
StudentService:
package com.jishou.service;
import com.jishou.pojo.Student;
import java.util.List;
public interface StudentService {
public List<Student> queryAllStudents();
public boolean addStudent(Student student);
public boolean deleteStudentById(Integer id);
public boolean updateStudent(Student student);
public Student queryOneStudentById(Integer id);
}
StudentServiceImpl:
package com.jishou.service;
import com.jishou.dao.StudentDao;
import com.jishou.dao.StudentDaoImpl;
import com.jishou.pojo.Student;
import java.util.List;
public class StudentServiceImpl implements StudentService{
private StudentDao studentDao=new StudentDaoImpl();
@Override
public List<Student> queryAllStudents() {
return studentDao.queryAllStudents();
}
@Override
public boolean addStudent(Student student) {
int row = studentDao.addStudent(student);
if(row>0){
return true;
}
return false;
}
@Override
public boolean deleteStudentById(Integer id) {
int row = studentDao.deleteStudentById(id);
if(row>0){
return true;
}
return false;
}
@Override
public boolean updateStudent(Student student) {
int row = studentDao.updateStudent(student);
if(row>0){
return true;
}
return false;
}
@Override
public Student queryOneStudentById(Integer id) {
return studentDao.queryOneStudentById(id);
}
}
- servlet:
AddServlet:
package com.jishou.servlet;
import com.jishou.pojo.Student;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
import com.jishou.util.DateUtil;
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.Date;
@WebServlet(name = "AddServlet",urlPatterns = "/add")
public class AddServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//取参数值
req.setCharacterEncoding("utf-8");
String sname = req.getParameter("sname");
//将String的年龄转换为int类型
Integer age = Integer.parseInt(req.getParameter("age"));
String date = req.getParameter("birthday");
//将String日期类型转换为java.util.Date
Date birthday = DateUtil.strToUtilDate(date);
String address = req.getParameter("address");
String photo = req.getParameter("photo");
Student student=new Student(sname,age,birthday,address,photo);
//实现修改逻辑
boolean flag = studentService.addStudent(student);
if(flag){
//添加成功
resp.sendRedirect("list");
}else{
//添加失败
resp.sendRedirect("add.jsp");
}
}
}
删除功能:
- 前台:list.jsp:
<a href="delete?id=<%=s.getId()%>">删除</a>
- 后台:DeleteServlet:
package com.jishou.servlet;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
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;
@WebServlet(name = "DeleteServlet",urlPatterns = "/delete")
public class DeleteServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//取参
String ids = req.getParameter("id");
//类型转换
Integer id=Integer.parseInt(ids);
boolean flag = studentService.deleteStudentById(id);
if(flag){
resp.sendRedirect("list");
}
}
}
修改功能:
- list.jsp:
<a href="load?id=<%=s.getId()%>">修改</a>
-
LoadServlet:
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; 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; @WebServlet(name = "LoadServlet",urlPatterns = "/load") public class LoadServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Integer id=Integer.parseInt(req.getParameter("id")); //根据id查询单个 Student student = studentService.queryOneStudentById(id); req.setAttribute("s",student); //请求转发 req.getRequestDispatcher("update.jsp").forward(req,resp); } }
-
update.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <center> <h1>修改学生</h1> <form action="update" method="post"> <table width="50%" height="35%"> <tr> <td>编号</td> <td><input type="text" name="id" value="${s.id}" readonly></td> </tr> <tr> <td>姓名</td> <td><input type="text" name="sname" value="${s.sname}"></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="age" value="${s.age}"></td> </tr> <tr> <td>生日</td> <td><input type="date" name="birthday" value="${s.birthday}"></td> </tr> <tr> <td>地址</td> <td><input type="text" name="address" value="${s.address}"></td> </tr> <tr> <td>头像</td> <td><input type="text" name="photo" value="${s.photo}"></td> </tr> <tr> <td><input type="submit" value="修改"></td> <td><input type="reset" name="重置"></td> </tr> </table> </form> </center> </body> </html>
-
UpdateServlet:
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; import com.jishou.util.DateUtil; 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.Date; @WebServlet(name = "UpdateServlet",urlPatterns = "/update") public class UpdateServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取参数值 req.setCharacterEncoding("utf-8"); Integer id = Integer.parseInt(req.getParameter("id")); String sname = req.getParameter("sname"); //将String的年龄转换为int类型 Integer age = Integer.parseInt(req.getParameter("age")); String date = req.getParameter("birthday"); //将String日期类型转换为java.util.Date Date birthday = DateUtil.strToUtilDate(date); String address = req.getParameter("address"); String photo = req.getParameter("photo"); Student student=new Student(id,sname,age,birthday,address,photo); //实现修改逻辑 boolean flag = studentService.updateStudent(student); if(flag){ //修改成功 resp.sendRedirect("list"); }else{ //修改失败 resp.sendRedirect("update.jsp"); } } }
eg7: 使用Servlet实现学生信息的分页展示
-
编写PageBean : PageBean对象就是当前页面对象,包含了当前页面所包含的所有信息
package com.jishou.pojo; import java.util.List; /** * 存放分页相关的数据 * */ public class PageBean<T> { //基本属性 private int currentPageNum;//当前页数,由用户指定 private int pageSize = 5;//每页显示的条数,固定的 private int totalRecords;//总记录条数,数据库查出来的 private int totalPageNum;//总页数,计算出来的 private List<T> list;//已经分好页的结果集 public int getCurrentPageNum() { return currentPageNum; } public void setCurrentPageNum(int currentPageNum) { this.currentPageNum = currentPageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalRecords() { return totalRecords; } public void setTotalRecords(int totalRecords) { this.totalRecords = totalRecords; //总记录数固定,页面大小固定,计算出总页数 if(this.totalRecords%this.pageSize==0){ this.totalPageNum=this.totalRecords/this.pageSize; }else{ this.totalPageNum=this.totalRecords/this.pageSize+1; } } public int getTotalPageNum() { return totalPageNum; } public void setTotalPageNum(int totalPageNum) { this.totalPageNum = totalPageNum; } public List getList() { return list; } public void setList(List list) { this.list = list; } @Override public String toString() { return "PageBean{" + "currentPageNum=" + currentPageNum + ", pageSize=" + pageSize + ", totalRecords=" + totalRecords + ", totalPageNum=" + totalPageNum + ", list=" + list + '}'; } }
-
dao层编写 获取总记录数和分页查询的逻辑
StudentDao:
//查询总记录数 public int getTotalRecords(); //分页查询学生信息 参数为当前页和页面大小 public List<Student> queryStudentsByPage(int currentPage,int pageSize);
StudentDaoImpl:
@Override public int getTotalRecords() { String sql="select count(*) from stu"; Connection conn = DBUtil.getConnection(); PreparedStatement pstmt=null; ResultSet rs=null; int count=0; try { pstmt= conn.prepareStatement(sql); rs= pstmt.executeQuery(); if (rs.next()) { count = rs.getInt(1); } }catch (SQLException e){ e.printStackTrace(); }finally { DBUtil.close(rs,pstmt,conn); } return count; } @Override public List<Student> queryStudentsByPage(int currentPage, int pageSize) { String sql="select * from stu limit ?,?"; Connection conn = DBUtil.getConnection(); List<Student> list = new ArrayList<>(); PreparedStatement pstmt=null; ResultSet rs=null; try { pstmt= conn.prepareStatement(sql); //注意第一个参数值的写法 pstmt.setInt(1,(currentPage-1)*pageSize); pstmt.setInt(2,pageSize); rs= pstmt.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String sname = rs.getString(2); int age = rs.getInt(3); Date birthday = rs.getDate(4); String address = rs.getString(5); String photo = rs.getString(6); Student student = new Student(id, sname, age, birthday, address, photo); list.add(student); } }catch (SQLException e){ e.printStackTrace(); }finally { DBUtil.close(rs,pstmt,conn); } return list; }
-
service层代码
StudentService:
//分页查询学生信息 参数为当前页和页面大小 public PageBean<Student> queryStudentsByPage(int currentPage, int pageSize);
StudentServiceImpl:
@Override public PageBean<Student> queryStudentsByPage(int currentPage, int pageSize) { List<Student> students = studentDao.queryStudentsByPage(currentPage, pageSize); int total = studentDao.getTotalRecords(); PageBean<Student> pageBean=new PageBean<>(); pageBean.setPageSize(pageSize);//设置页面大小 pageBean.setTotalRecords(total);//设置总记录数 pageBean.setCurrentPageNum(currentPage);//设置当前页 pageBean.setList(students);//设置当前页数据 return pageBean; }
-
ListPageServlet 分页的Servlet
ListPageServlet:
package com.jishou.servlet; import com.jishou.pojo.PageBean; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; 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(name = "ListPageServlet",urlPatterns = "/listpage") public class ListPageServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取当前页 String currentPage= req.getParameter("currentPage"); //第一次访问,默认currentPage 访问第一页 if(currentPage==null) { currentPage = "1"; } Integer currentPageNum=Integer.parseInt(currentPage); //页面大小暂设置成固定值3 //分页查询所有 PageBean<Student> pageBean = studentService.queryStudentsByPage(currentPageNum,3); //servlet重在业务逻辑,取值传值 jsp侧重于页面显示 req.setAttribute("page",pageBean); //请求转发 req.getRequestDispatcher("listpage.jsp").forward(req,resp); } }
注意:
登录成功之后跳转到llistpage
response.sendRedirect("listpage");
-
前端 listpage.jsp
<%@ page import="com.jishou.pojo.Student" %> <%@ page import="java.util.List" %> <%@ page import="com.jishou.pojo.User" %> <%@ page import="com.jishou.pojo.PageBean" %> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> <style> #login{ float: left; } #count{ float: right; } </style> </head> <body> <div id="login">欢迎${sessionScope.user.username}登录 <a href="logout">退出系统</a></div> <div id="count">当前共有${applicationScope.count}人在线</div> <center> <h1>学生管理系统</h1> <table width="70%" height="50%"> <tr> <td>头像</td> <td>Id</td> <td>姓名</td> <td>年龄</td> <td>生日</td> <td>地址</td> <td> <a href="add.jsp">添加学生</a> </td> </tr> <c:if test="${requestScope.page!=null}"> <c:if test="${requestScope.page.list ne null and requestScope.page.list.size() gt 0}"> <c:forEach var="s" items="${requestScope.page.list}"> <tr> <td> <img src="${s.photo}" width="20px" height="20px"/> </td> <td>${s.id}</td> <td>${s.sname}</td> <td>${s.age}</td> <td>${s.birthday}</td> <td>${s.address}</td> <td> <a href="load?id=${s.id}">修改</a> <a href="delete?id=${s.id}">删除</a> </td> </tr> </c:forEach> </c:if> </c:if> <tr> <td colspan="7"> <input type="button" value="首页" onclick="toFirst()"> <input type="button" value="上一页" onclick="toPrev()"> 当前页 ${requestScope.page.currentPageNum}| ${requestScope.page.totalPageNum} 总页数 <input type="button" value="下一页" onclick="toNext()"> <input type="button" value="末页" onclick="toLast()"> </td> </tr> </table> </center> </body> <script> var currentPage=${requestScope.page.currentPageNum}; var totalPage=${requestScope.page.totalPageNum}; function toFirst() { location.href="listpage?currentPage=1"; } function toPrev() { //控制页面显示风格 var url=""; if(currentPage=1){ url="listpage?currentPage=1"; }else{ url="listpage?currentPage="+(currentPage-1); } location.href=url; } function toNext() { //控制页面显示风格 var url=""; if(currentPage=totalPage){ url="listpage?currentPage="+totalPage; }else{ url="listpage?currentPage="+(currentPage+1); } location.href=url; } function toLast() { location.href="listpage?currentPage="+${requestScope.page.totalPageNum}; } </script> </html>
-
浏览器访问 从login.html开始访问
eg8: 使用Servlet实现学生头像的上传功能
通过为表单元素设置method=“post” enctype=“multipart/form-data” 属性,让表单提交的数据以二进制编码的方式提交,在接受此请求的servlet中的二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。
-
前端页面 上传表单 add.jsp
注意: form表单元素必须设置method=“post” enctype=“multipart/form-data” 属性
add.jsp
<form action="add" method="post" enctype="multipart/form-data"> <table width="50%" height="35%"> <tr> <td>头像</td> <td>请选择图片:<input type="file" name="photo"></td> </tr> ........ <tr> <td><input type="submit" value="添加"></td> <td><input type="reset" name="重置"></td> </tr> </table> </form>
-
后台上传功能的实现
由于添加功能里面需要图片属性需要上传,所有上传的逻辑写在AddServlet里面了
AddServlet:
!(img\tupian.png)
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; import com.jishou.util.DateUtil; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.UUID; @MultipartConfig //使用MultipartConfig注解标注改servlet能够接受文件上传的请求 @WebServlet(name = "AddServlet",urlPatterns = "/add") public class AddServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); //1. 上传逻辑 Part part = req.getPart("photo"); //获取上传文件的文件名 String filename=part.getSubmittedFileName(); String serverpath="G:\\idea_workspace\\stuManage_04\\web\\img\\"; InputStream in = part.getInputStream(); FileOutputStream fos = new FileOutputStream(serverpath + filename); byte[] bytes=new byte[1024]; int length=0; while((length=in.read(bytes))!=-1){ fos.write(bytes,0,length); } fos.close(); in.close(); //2. 添加逻辑 //取参数值 String sname = req.getParameter("sname"); //将String的年龄转换为int类型 Integer age = Integer.parseInt(req.getParameter("age")); String date = req.getParameter("birthday"); //将String日期类型转换为java.util.Date Date birthday = DateUtil.strToUtilDate(date); String address = req.getParameter("address"); //String photo = req.getParameter("photo"); String photo="img/"+filename; Student student=new Student(sname,age,birthday,address,photo); //实现修改逻辑 boolean flag = studentService.addStudent(student); if(flag){ //添加成功 resp.sendRedirect("listpage"); }else{ //添加失败 resp.sendRedirect("add.jsp"); } } }
注意:如果上传之后图片没有及时更新,参考下面,修改下tomcat配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oGT7j9n3-1638964004210)(img/tupian.png)]
eg9: 实现在项目中添加安全过滤器,用户未经登录不能访问系统,通过Filter统一实现设置字符编码
安全过滤器:
用户未经登录不能访问其他逻辑,所以需要Filter来实现
new —>create new Filter---->就会按模板生成
需要配置过滤路径 urlPatterns = "/" / * 表示过滤所有
思路: 编写Filter,判断session中user对象是否为null;如果为null,说明未经登录,拦截,回到login.html;
但用户登录或注册时session还未创建,此时user==null;但要保证正常的登录,注册,就必须判断 如果是登录或注册的话,就放行
如果login.html或者register.html中文乱码的话,把他们改成jsp文件即可
- 编写LoginFilter:
package com.jishou.filter;
import com.jishou.pojo.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "EncodingFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request= (HttpServletRequest) req;
HttpServletResponse response= (HttpServletResponse) resp;
//session中取用户信息
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
//判断用户是否登录
//获取请求路径
String path = request.getRequestURI();
System.out.println("path: "+path);
if(user!=null){
//放行
chain.doFilter(req, resp);
return;
}else {
//登录和注册需要放行
if (path.endsWith("login.html") || path.endsWith("register.html") || path.endsWith("login") || path.endsWith("register")) {
//放行
chain.doFilter(req, resp);
return;
}else{
response.sendRedirect("login.html");
}
}
}
public void init(FilterConfig config) throws ServletException {
}
}
2.浏览器测试访问
http://localhost:8080/stuManage_04_war_exploded/list
此时会无法访问列表,会自动重定向到login.html
字符编码过滤器:
通常处理request中的post方式的中文乱码和response中的中文乱码时,需要再servlet里面调用setCharacterEncoding()方法;可以设置过滤器,在Filter里面实现过滤,那么在servlet里面就不需要再单独设置编码了
-
编写CharacterFilter
package com.jishou.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @WebFilter(filterName = "CharacterFilter",urlPatterns = "/*") public class CharacterFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); chain.doFilter(req, resp); } public void init(FilterConfig config) throws ServletException { } }
-
将Servlet里面处理中文编码的方法去掉
去掉
//req.setCharacterEncoding("utf-8");
-
浏览器访问测试
eg10:通过Listener来实现统计在线人数功能:
LoginServlet和LogoutServlet里面统计在线访问人数的逻辑去掉
CountListener:
package com.jishou.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
@WebListener()
public class CountListener implements
HttpSessionAttributeListener {
private int count=0;
public void attributeAdded(HttpSessionBindingEvent sbe) {
HttpSession session = sbe.getSession();
ServletContext servletContext = session.getServletContext();
servletContext.setAttribute("count",++count);
}
public void attributeRemoved(HttpSessionBindingEvent sbe) {
HttpSession session = sbe.getSession();
ServletContext servletContext = session.getServletContext();
servletContext.setAttribute("count",--count);
}
public void attributeReplaced(HttpSessionBindingEvent sbe) {
/* This method is invoked when an attribute
is replaced in a session.
*/
}
}
eg10: 使用jquery+ajax实现添加用户时自动检查用户名是否已存在,并给予相应提示功能
-
add.jsp里面 使用jquery+ajax异步访问后台
需要引入jquery的库文件,放在web/js目录底下 jquery-1.8.3.js
add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <script src="js/jquery-1.8.3.js"></script> <script> function checkName() { var sname=$("#sname").val(); console.log(sname); $.post( //使用post请求 'checkName', //访问后台的url路径 {"sname":sname},//往后台传的参数 //回调函数 就使后台执行完毕之后再执行的函数 data表示后台执行的结果,返回的值 function (data) { console.log(data); if(data==1){ //用户名存在 $("#ff").html("用户名已存在!!!请重新输入...") }else{ $("#ff").html("该用户名不存在!!!可以使用...") } } ) } </script> <body> <center> <h1>添加学生</h1> <form action="add" method="post" enctype="multipart/form-data"> <table width="50%" height="35%"> <tr> <td>姓名</td> <td><input type="text" name="sname" id="sname" onblur="checkName()"> <font id="ff" color="red" size="2"></font> </td> </tr> ........ </table> </form> </center> </body> </html>
说明:
$("#sname") 表示取得id="sname"的标签对象 .val() 取该对象的value值
$.post() 是通过jquery来实现ajax异步和后台交互 使用post请求方式
$("#ff").html(" ") 表示往id="ff"的标签中间写入相应内容
οnblur="" 光标丢失事件
-
后台servlet编写代码
CheckSnameServlet
package com.jishou.servlet; import com.jishou.pojo.Student; import com.jishou.service.StudentService; import com.jishou.service.StudentServiceImpl; 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.io.PrintWriter; @WebServlet(name = "CheckSnameServlet",urlPatterns = "/checkName") public class CheckSnameServlet extends HttpServlet { private StudentService studentService=new StudentServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. 取参数值 req.setCharacterEncoding("utf-8"); String sname = req.getParameter("sname"); //2.连数据库查询 //true 存在 false不存在 boolean flag= studentService.queryStudentBySname(sname); //3.响应 必须输出到浏览器页面上 resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); if(flag){ //用户名存在 out.println(1); }else { //用户名不存在 out.println(0); } out.flush(); out.close(); } }
-
后台service接口及其实现类
StudentService
//判断用户名是否存在 public boolean queryStudentBySname(String sname);
StudentServiceImpl
@Override public boolean queryStudentBySname(String sname) { return studentDao.queryStudentBySname(sname); }
-
后台dao接口及其实现类
StudentDao:
//判断用户名是否存在
public boolean queryStudentBySname(String sname);
StudentDaoImpl
@Override
public boolean queryStudentBySname(String sname) {
String sql="select * from stu where sname=?";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
ResultSet rs=null;
Student student=null;
try {
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,sname);
rs= pstmt.executeQuery();
if (rs.next()) {
return true;
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(rs,pstmt,conn);
}
return false;
}
-
浏览器访问测试效果
在add.jsp里面输入用户名后,光标丢失,就会自动判断输入的用户名是否存在,并给予提示
eg11:实现首页上左右布局:
-
创建index.jsp head.jsp left.jsp
-
使用frameset实现页面布局
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <frameset rows="15%,*" border="1"> <frame src="head.jsp"> <!-- 引用左边和主体部分 --> <frameset cols="18%,*" border="1"> <frame src="left.jsp" name="leftmenu"> <frame src="main.jsp" name="main"> </frameset> </frameset> </html>
head.jsp
可以在head.jsp放些公司logo;欢迎XXX
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <div id="login">欢迎${sessionScope.user.username}登录 </div> <div id="count">当前共有${applicationScope.count}人在线</div> </body> </html>
left.jsp:
注意:学生列表和添加学生超链接执向的地址,和target="main"的值,要在name="main"那个frame里面呈现
<a href="logout" target="_parent">退出系统</a> target="_parent" 表示调到父组件
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <div> <a href="#" target="main">首页</a> <dl> <dt> 学生管理 </dt> <dd> <a href="listpage" target="main">学生列表</a> </dd> <dd> <a href="add.jsp" target="main">添加学生</a> </dd> </dl> <dl> <dt> 班级管理 </dt> <dd> <a href="" target="main">班级列表</a> </dd> <dd> <a href="" target="main">添加班级</a> </dd> </dl> <dl> <dt> 系统管理 </dt> <dd> <a href="" target="main">修改密码</a> </dd> <dd> <a href="logout" target="_parent">退出系统</a> </dd> </dl> </div> </body> </html>
LoginServlet: 登录成功之后直接跳到首页
response.sendRedirect("index.jsp");
eg12:实现正则验证:
在register.jsp里面设计常用的几个字段:手机号码,身份证号码,邮箱等,通过正则表达式实现验证:
正则语法可以参考菜鸟教程:
https://www.runoob.com/regexp/regexp-tutorial.html
register.jsp:
需要引入jquery文件:οnblur="" 光标丢失事件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
function checkUserName(){
var username = $("input[name='username']").val();
var pattern=/^.{6,20}$/;// 6-20个字符组成
if(!pattern.test(username)){
alert("用户名长度必须是6-20个字符组成");
}
}
function checkPassword(){
var password = $("input[name='password']").val();
var pattern=/^[a-zA-Z]\w{5,17}$/;// 以字母开头,长度在6~18之间,只能包含字母、数字和下划线
if(!pattern.test(password)){
alert("密码必须以字母开头,长度在6~18之间,只能包含字母、数字和下划线");
}
}
function checkPhone(){
var phone = $("input[name='phone']").val();
var pattern=/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;// 11位手机号码
if(!pattern.test(phone)){
alert("请输入正确的手机号码格式");
}
}
function checkIdCard(){
var idCard = $("input[name='idcard']").val();
var pattern=/^\d{15}|\d{18}$/;// 15或18位身份证号码
if(!pattern.test(idCard)){
alert("请输入正确的身份证号码格式");
}
}
function checkEmail(){
var email = $("input[name='email']").val();
var pattern=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;// 邮箱格式
if(!pattern.test(email)){
alert("请输入正确的邮箱号码格式");
}
}
</script>
<body>
<h1>注册页面</h1>
<!--前端访问路径都不加/ -->
<form action="register" method="post">
用户名: <input type="text" name="username" onblur="checkUserName()"><br>
密码: <input type="password" name="password" onblur="checkPassword()"><br>
手机号码: <input type="text" name="phone" onblur="checkPhone()"><br>
身份证号码: <input type="text" name="idcard" onblur="checkIdCard()"><br>
邮箱: <input type="text" name="email" onblur="checkEmail()"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
附: 正则表达式大全
一、校验数字的表达式
1. 数字:^[0-9]*$
2. n位的数字:^\d{n}$
3. 至少n位的数字:^\d{n,}$
4. m-n位的数字:^\d{m,n}$
5. 零和非零开头的数字:^(0|[1-9][0-9]*)$
6. 非零开头的最多带两位小数的数字:^([1-9][0-9]*)+(.[0-9]{1,2})?$
7. 带1-2位小数的正数或负数:^(\-)?\d+(\.\d{1,2})?$
8. 正数、负数、和小数:^(\-|\+)?\d+(\.\d+)?$
9. 有两位小数的正实数:^[0-9]+(.[0-9]{2})?$
10. 有1~3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$
11. 非零的正整数:^[1-9]\d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^\+?[1-9][0-9]*$
12. 非零的负整数:^\-[1-9][]0-9"*$ 或 ^-[1-9]\d*$
13. 非负整数:^\d+$ 或 ^[1-9]\d*|0$
14. 非正整数:^-[1-9]\d*|0$ 或 ^((-\d+)|(0+))$
15. 非负浮点数:^\d+(\.\d+)?$ 或 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$
16. 非正浮点数:^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 或 ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$
17. 正浮点数:^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 或 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$
18. 负浮点数:^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ 或 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$
19. 浮点数:^(-?\d+)(\.\d+)?$ 或 ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$
二、校验字符的表达式
1. 汉字:^[\u4e00-\u9fa5]{0,}$
2. 英文和数字:^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$
3. 长度为3-20的所有字符:^.{3,20}$
4. 由26个英文字母组成的字符串:^[A-Za-z]+$
5. 由26个大写英文字母组成的字符串:^[A-Z]+$
6. 由26个小写英文字母组成的字符串:^[a-z]+$
7. 由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$
8. 由数字、26个英文字母或者下划线组成的字符串:^\w+$ 或 ^\w{3,20}$
9. 中文、英文、数字包括下划线:^[\u4E00-\u9FA5A-Za-z0-9_]+$
10. 中文、英文、数字但不包括下划线等符号:^[\u4E00-\u9FA5A-Za-z0-9]+$ 或 ^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$
11. 可以输入含有^%&',;=?$\"等字符:[^%&',;=?$\x22]+ 12 禁止输入含有~的字符:[^~\x22]+
三、特殊需求表达式
1. Email地址:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
2. 域名:[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?
3. InternetURL:[a-zA-z]+://[^\s]* 或 ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$
4. 手机号码:^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$
5. 电话号码("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX):^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$
6. 国内电话号码(0511-4405222、021-87888822):\d{3}-\d{8}|\d{4}-\d{7}
7. 身份证号(15位、18位数字):^\d{15}|\d{18}$
8. 短身份证号码(数字、字母x结尾):^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$
9. 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
10. 密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):^[a-zA-Z]\w{5,17}$
11. 强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间):^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
12. 日期格式:^\d{4}-\d{1,2}-\d{1,2}
13. 一年的12个月(01~09和1~12):^(0?[1-9]|1[0-2])$
14. 一个月的31天(01~09和1~31):^((0?[1-9])|((1|2)[0-9])|30|31)$
15. 钱的输入格式:
16. 1.有四种钱的表示形式我们可以接受:"10000.00" 和 "10,000.00", 和没有 "分" 的 "10000" 和 "10,000":^[1-9][0-9]*$
17. 2.这表示任意一个不以0开头的数字,但是,这也意味着一个字符"0"不通过,所以我们采用下面的形式:^(0|[1-9][0-9]*)$
18. 3.一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号:^(0|-?[1-9][0-9]*)$
19. 4.这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分:^[0-9]+(.[0-9]+)?$
20. 5.必须说明的是,小数点后面至少应该有1位数,所以"10."是不通过的,但是 "10" 和 "10.2" 是通过的:^[0-9]+(.[0-9]{2})?$
21. 6.这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样:^[0-9]+(.[0-9]{1,2})?$
22. 7.这样就允许用户只写一位小数.下面我们该考虑数字中的逗号了,我们可以这样:^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$
23 8.1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须:^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$
24. 备注:这就是最终结果了,别忘了"+"可以用"*"替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里
25. xml文件:^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$
26. 中文字符的正则表达式:[\u4e00-\u9fa5]
27. 双字节字符:[^\x00-\xff] (包括汉字在内,可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1))
28. 空白行的正则表达式:\n\s*\r (可以用来删除空白行)
29. HTML标记的正则表达式:<(\S*?)[^>]*>.*?</\1>|<.*? /> (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力)
30. 首尾空白字符的正则表达式:^\s*|\s*$或(^\s*)|(\s*$) (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式)
31. 腾讯QQ号:[1-9][0-9]{4,} (腾讯QQ号从10000开始)
32. 中国邮政编码:[1-9]\d{5}(?!\d) (中国邮政编码为6位数字)
33. IP地址:\d+\.\d+\.\d+\.\d+ (提取IP地址时有用)
34. IP地址:((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))
eg13: 使用cookie完成记住密码功能和异步登录功能
注意: 如果访问login.jsp,浏览器页面提示js文件访问不到404的话,可以吧js目录删掉再重新新建一下,再把js文件放进去
login.jsp
注意:需要引入3个js文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript" src="js/jquery.base64.js"></script>
<script type="text/javascript">
//设置cookie
function setCookie(){
var loginCode = $("#zhanghao").val(); //获取用户名信息
var pwd = $("#mima").val(); //获取登陆密码信息
var checked = $("input[type='checkbox']").is(':checked');//获取“是否记住密码”复选框
//console.log("setCookie方法是否记住密码:"+checked);
if(checked){ //判断是否选中了“记住密码”复选框
//设置cookie过期时间
var date = new Date();
date.setTime(date.getTime()+60*1000);//只能这么写,60表示60秒钟
//console.log("cookie过期时间:"+date);
$.cookie("login_code",loginCode,{ expires: date, path: '/' });//调用jquery.cookie.js中的方法设置cookie中的用户名
$.cookie("pwd",$.base64.encode(pwd),{ expires: date, path: '/' });//调用jquery.cookie.js中的方法设置cookie中的登陆密码,并使用base64(jquery.base64.js)进行加密
}else{
$.cookie("login_code", null);
$.cookie("pwd", null);
}
}
//清除所有cookie函数
function clearAllCookie() {
var date=new Date();
date.setTime(date.getTime()-10000);
var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
console.log("需要删除的cookie名字:"+keys);
if (keys) {
for (var i = keys.length; i--;)
document.cookie=keys[i]+"=0; expire="+date.toGMTString()+"; path=/";
}
}
//获取cookie
function getCookie(){
var loginCode = $.cookie("login_code"); //获取cookie中的用户名
var pwd = $.cookie("pwd"); //获取cookie中的登陆密码
console.log("获取cookie:账户:"+loginCode);
console.log("获取cookie:密码:"+pwd);
if (!loginCode||loginCode==0) {
console.log("账户:"+!loginCode);
//alert("请输出内容!");
}else{
$("#zhanghao").val(loginCode);
}
if(!pwd||pwd==0){
console.log("密码:"+!pwd);
}else{
//密码存在的话把密码填充到密码文本框
//console.log("密码解密后:"+$.base64.decode(pwd));
$("#mima").val($.base64.decode(pwd));
//密码存在的话把“记住用户名和密码”复选框勾选住
$("[name='jizhu']").attr("checked","true");
}
}
function checkLogin(){
var userName = $('#zhanghao').val();
console.log("用户名:"+userName);
if(userName == ''){
alert("请输入用户名。");
return;
}
var userPass =$('#mima').val();
console.log("密码:"+userPass);
if(userPass == ''){
alert("请输入密码。");
return;
}
//判断是否选中复选框,如果选中,添加cookie
var jizhupwd=$("input[type='checkbox']").is(':checked');
console.log("是否记住密码:"+jizhupwd);
if(jizhupwd){
//添加cookie
setCookie();
}else{
clearAllCookie();
}
login(userName,userPass);//联网上传账号密码
}
//异步登录逻辑
function login(username,password){
console.log(username+" "+password);
$.post(
"login",
{
"username": username,
"password": password,
},
function(data) {
if (data == 1) {
alert("登录成功");
location.href = "index.jsp";
} else {
alert("登录失败");
}
}
);
}
</script>
<body onload="getCookie()">
<h1>登录页面</h1>
<!--前端访问路径都不加/ -->
<form>
用户名: <input type="text" name="username" id="zhanghao"><br>
密码: <input type="password" name="password" id="mima"><br>
<input type="checkbox" name="jizhu">记住密码<br>
<input type="button" value="登录" id="denglu" onclick="checkLogin()">
<a href="register.jsp">立即注册</a>
</form>
</body>
</html>
LoginServlet改造:
package com.jishou.servlet;
import com.jishou.pojo.User;
import com.jishou.service.UserService;
import com.jishou.service.UserServiceImpl;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
//private Integer count=0;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 取前台参数
//request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User qtuser=new User(username,password);
//2. 连接数据库查询
User htuser = userService.login(qtuser);
//3. 判断登录是否成功
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if(htuser!=null){
HttpSession session = request.getSession();
session.setAttribute("user",htuser);
out.println(1);
}else{
out.println(0);
}
out.flush();
out.close();
}
}
eg14: 批量删除功能
listpage.jsp
该页面里面需要写生全选,反选,全不选的实现逻辑,并且获取选中的id值,拼接成字符串,并通过ajax实现批量删除的逻辑
$(function(){}) 是jquery里面的文档就绪函数 ,表示页面加载完毕就执行的逻辑,相当于js的window.onload事件;
最后将选中的id值直接作为字符串拼接;比如选中2和3;那参数ids=2,3
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script>
$(
function () {
//全选
$("#qx").click(
function(){
$(".one").attr("checked",true);
}
),
//全不选
$("#qbx").click(
function(){
$(".one").attr("checked",false);
}
),
//反选
$("#fx").click(
function(){
$(".one").each(function(){
$(this).attr("checked",!$(this).attr("checked"));
})
}
)
}
)
//批量删除
function plsc(){
var ids="";
$(".one:checked").each(
function(){
var id=$(this).val();
ids+=","+id;
}
)
ids=ids.substring(1);
console.log("ids="+ids);
$.post(
'deleteplsc',
{ids:ids},
function(obj){
if(obj==1){
alert("删除成功");
location="listpage";
}else{
alert("删除失败");
}
},
'json'
)
}
</script>
<div>
<input type="button" value="批量删除" onclick="plsc()">
</div>
<tr>
<td>
<input type="button" id="qx" value="全选" >
<input type="button" id="qbx" value="全不选">
<input type="button" id="fx" value="反选">
</td>
........
</tr>
<c:forEach var="s" items="${requestScope.page.list}">
<tr>
<td>
<input type="checkbox" class="one" value="${s.id }">
</td>
</c:forEach>
。。。。。。。
listpage.jsp 完整代码如下:
<%@ page import="com.jishou.pojo.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="com.jishou.pojo.User" %>
<%@ page import="com.jishou.pojo.PageBean" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<style>
#login{
float: left;
}
#count{
float: right;
}
</style>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script>
$(
function () {
//全选
$("#qx").click(
function(){
$(".one").attr("checked",true);
}
),
//全不选
$("#qbx").click(
function(){
$(".one").attr("checked",false);
}
),
//反选
$("#fx").click(
function(){
$(".one").each(function(){
$(this).attr("checked",!$(this).attr("checked"));
})
}
)
}
)
//批量删除
function plsc(){
var ids="";
$(".one:checked").each(
function(){
var id=$(this).val();
ids+=","+id;
}
)
ids=ids.substring(1);
console.log("ids="+ids);
$.post(
'deleteplsc',
{ids:ids},
function(obj){
if(obj==1){
alert("删除成功");
location="listpage";
}else{
alert("删除失败");
}
},
'json'
)
}
</script>
<center>
<h1>学生管理系统</h1>
<div>
<input type="button" value="批量删除" onclick="plsc()">
</div>
<table width="70%" height="50%">
<tr>
<td>
<input type="button" id="qx" value="全选" >
<input type="button" id="qbx" value="全不选">
<input type="button" id="fx" value="反选">
</td>
<td>头像</td>
<td>Id</td>
<td>姓名</td>
<td>年龄</td>
<td>生日</td>
<td>地址</td>
<td>
<a href="add.jsp">添加学生</a>
</td>
</tr>
<c:if test="${requestScope.page!=null}">
<c:if test="${requestScope.page.list ne null and requestScope.page.list.size() gt 0}">
<c:forEach var="s" items="${requestScope.page.list}">
<tr>
<td>
<input type="checkbox" class="one" value="${s.id }">
</td>
<td>
<img src="${s.photo}" width="20px" height="20px"/>
</td>
<td>${s.id}</td>
<td>${s.sname}</td>
<td>${s.age}</td>
<td>${s.birthday}</td>
<td>${s.address}</td>
<td>
<a href="load?id=${s.id}">修改</a>
<a href="delete?id=${s.id}">删除</a>
</td>
</tr>
</c:forEach>
</c:if>
</c:if>
<tr>
<td colspan="7">
<input type="button" value="首页" onclick="toFirst()">
<input type="button" value="上一页" onclick="toPrev()">
当前页 ${requestScope.page.currentPageNum}| ${requestScope.page.totalPageNum} 总页数
<input type="button" value="下一页" onclick="toNext()">
<input type="button" value="末页" onclick="toLast()">
</td>
</tr>
</table>
</center>
</body>
<script>
var currentPage=${requestScope.page.currentPageNum};
var totalPage=${requestScope.page.totalPageNum};
function toFirst() {
location.href="listpage?currentPage=1";
}
function toPrev() {
//控制页面显示风格
var url="";
if(currentPage=1){
url="listpage?currentPage=1";
}else{
url="listpage?currentPage="+(currentPage-1);
}
location.href=url;
}
function toNext() {
//控制页面显示风格
var url="";
if(currentPage=totalPage){
url="listpage?currentPage="+totalPage;
}else{
url="listpage?currentPage="+(currentPage+1);
}
location.href=url;
}
function toLast() {
location.href="listpage?currentPage="+${requestScope.page.totalPageNum};
}
</script>
</html>
后台:
DeletePlscServlet:
package com.jishou.servlet;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "DeletePlscServlet",urlPatterns = "/deleteplsc")
public class DeletePlscServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String ids = req.getParameter("ids");
System.out.println("ids: "+ids);
boolean flag=studentService.deleteStudentByBatch(ids);
PrintWriter out = resp.getWriter();
if(flag){
out.println(1);
}else{
out.println(0);
}
out.flush();
out.close();
}
}
StudentService:
//批量删除
public boolean deleteStudentByBatch(String ids);
StudentServiceImpl:
@Override
public boolean deleteStudentByBatch(String ids) {
String[] idStr = ids.split(",");
int row=0;
for(String id:idStr){
row = studentDao.deleteStudentById(Integer.parseInt(id));
}
if(row>0){
return true;
}
return false;
}
eg15: 模糊查询和区间查询功能
方便起见,在这里面直接模糊查询和区间查询没有分页,直接写在list.jsp了
list.jsp:
在table表格上面写生查询的表单:根据姓名模糊查询和根据生日区间查询
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style>
#login{
float: left;
}
#count{
float: right;
}
</style>
</head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script>
$(function () {
//日期框设置默认值
var time = new Date();
var day = ("0" + time.getDate()).slice(-2);
var month = ("0" + (time.getMonth() + 1)).slice(-2);
var today = time.getFullYear() + "-" + (month) + "-" + (day);
$('#begin').val(today);
$('#end').val(today);
})
</script>
<body>
<%
List<Student> list = (List<Student>) request.getAttribute("list");
User user = (User) request.getSession().getAttribute("user");
%>
<div id="login">欢迎<%=user.getUsername()%>登录 <a href="logout">退出系统</a></div>
<div id="count">当前共有<%=application.getAttribute("count")%>人在线</div>
<center>
<h1>学生管理系统</h1>
<form action="condition" method="post">
姓名: <input type="text" name="name" value="${c.name}">
开始时间: <input type="date" name="begin" id="begin">
结束时间: <input type="date" name="end" id="end">
<input type="submit" value="搜索">
</form>
<table width="70%" height="50%">
..............
</table>
</center>
</body>
</html>
Condition:
由于查询的条件有多个,为了方便起见,将查询的条件封装在对象Condition里面,pojo包里面
package com.jishou.pojo;
import java.util.Date;
public class Condition {
private String name;
private Date begin;//开始时间
private Date end;//结束时间
public Condition() {
}
public Condition(String name, Date begin, Date end) {
this.name = name;
this.begin = begin;
this.end = end;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBegin() {
return begin;
}
public void setBegin(Date begin) {
this.begin = begin;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
@Override
public String toString() {
return "Condition{" +
"name='" + name + '\'' +
", begin=" + begin +
", end=" + end +
'}';
}
}
ConditionServlet:
package com.jishou.servlet;
import com.jishou.pojo.Condition;
import com.jishou.pojo.Student;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
import com.jishou.util.DateUtil;
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.Date;
import java.util.List;
@WebServlet(name = "ConditionServlet",urlPatterns = "/condition")
public class ConditionServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
Date begin = DateUtil.strToUtilDate(req.getParameter("begin"));
Date end = DateUtil.strToUtilDate(req.getParameter("end"));
Condition condition=new Condition(name,begin,end);
List<Student> students= studentService.queryStudentsByCondition(condition);
//servlet重在业务逻辑,取值传值 jsp侧重于页面显示
req.setAttribute("list",students);
req.setAttribute("c",condition);
//请求转发
req.getRequestDispatcher("list.jsp").forward(req,resp);
}
}
StudentService:
//条件查询
public List<Student> queryStudentsByCondition(Condition condition);
StudentServiceImpl:
@Override
public List<Student> queryStudentsByCondition(Condition condition) {
return studentDao.queryStudentsByCondition(condition);
}
StudentDao:
//条件查询
public List<Student> queryStudentsByCondition(Condition condition);
StudentDaoImpl:
@Override
public List<Student> queryStudentsByCondition(Condition condition) {
String sql="";
Connection conn = DBUtil.getConnection();
List<Student> list = new ArrayList<>();
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
String name = condition.getName();
//判断要不要根据姓名模糊查询
if(name!=null&&!"".equals(name)){
sql="select * from stu where sname like ? and birthday between ? and ?";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,"%"+name+"%");
pstmt.setDate(2,DateUtil.toSqlDate(condition.getBegin()));
pstmt.setDate(3,DateUtil.toSqlDate(condition.getEnd()));
}else{
sql="select * from stu where birthday between ? and ?";
pstmt= conn.prepareStatement(sql);
pstmt.setDate(1,DateUtil.toSqlDate(condition.getBegin()));
pstmt.setDate(2,DateUtil.toSqlDate(condition.getEnd()));
}
rs= pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
String sname = rs.getString(2);
int age = rs.getInt(3);
Date birthday = rs.getDate(4);
String address = rs.getString(5);
String photo = rs.getString(6);
Student student = new Student(id, sname, age, birthday, address, photo);
list.add(student);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(rs,pstmt,conn);
}
return list;
}
eg16: 实现往数据库中批量导入100条数据
这里直接使用单元测试:
TestInsertBatch:
package com.jishou.test;
import com.jishou.pojo.Student;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Date;
public class TestInsertBatch {
StudentService studentService=new StudentServiceImpl();
@Test
public void testInsertBatch(){
String[] xing={"周","吴","郑","王","赵","钱","孙","李","张","陶","宋"};
String[] ming={"小米","小明","小刚","小花","小杰","小利","花花","小美"};
String[] address={"北京","洛阳","深圳","郑州","香港"};
for(int i=0;i<100;i++){
int xingIndex=(int)(Math.random()*(xing.length-1)+1);
int mingIndex=(int)(Math.random()*(ming.length-1)+1);
int addressIndex=(int)(Math.random()*(address.length-1)+1);
int age=(int)(Math.random()*(100)+1);
Date birthday=randomDate();
Student s=new Student(xing[xingIndex]+ming[mingIndex],age,birthday,address[addressIndex],"");
System.out.println(s);
studentService.addStudent(s);
}
}
//获取随机的日期类型的值
public static Date randomDate() {
int startYear=2016; //指定随机日期开始年份
int endYear=2018; //指定随机日期开始年份(含)
long start = Timestamp.valueOf(startYear+1+"-1-1 0:0:0").getTime();
long end = Timestamp.valueOf(endYear+"-1-1 0:0:0").getTime();
long ms=(long) ((end-start)*Math.random()+start); //获得了符合条件的13位毫秒数
Date birthday=new Date(ms);
return birthday;
}
}
直接运行testInsertBatch() 方法即可
eg17: 实现通过Echarts图表实现相同地域的学生个数的饼状图显示
在这里使用图表插件echarts
参考
官方文档demo: https://echarts.apache.org/examples/zh/index.html
Echarts菜鸟教程: https://www.runoob.com/echarts/echarts-tutorial.html
需要吧echarts的库文件echarts.min.js放到web的js目录底下
还需要复制fastjson-1.2.46.jar的依赖到lib目录底下,这个依赖能够实现json数据和java对象之间的转换
前端;
tubiao.jsp:
在这里,echarts里面的数据来自于后台,但数据格式是json格式的,属性必须叫name和value
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script type="text/javascript" src="js/echarts.min.js"></script>
<body>
${list}
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
series : [
{
name: '访问来源',
type: 'pie', // 设置图表类型为饼图
radius: '55%', // 饼图的半径,外半径为可视区尺寸(容器高宽中较小一项)的 55% 长度。
data: ${list}
/*[ // 数据数组,name 为数据项名称,value 为数据项值
{value:235, name:'视频广告'},
{value:274, name:'联盟广告'},
{value:310, name:'邮件营销'},
{value:335, name:'直接访问'},
{value:400, name:'搜索引擎'}
]*/
}
]
})
</script>
</body>
</html>
从后台查询出数据,List集合,但需要转换成json数据格式,使用fastjson里面的方法
echarts属性名必须叫name和value,所以封装一个javabean对象EchartsBean:
pojo实体类:
EchartsBean:
package com.jishou.pojo;
public class EchartsBean {
String name;
int value;
public EchartsBean() {
}
public EchartsBean(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return "EchartsBean{" +
"name='" + name + '\'' +
", value='" + value + '\'' +
'}';
}
}
dao层:
StudentDao:
//根据地址分组,查询各个区域的学生个数
public List<EchartsBean> findCountByAddress();
StudentDaoImpl:
@Override
public List<EchartsBean> findCountByAddress() {
String sql="select address,COUNT(*) from stu group by address";
Connection conn = DBUtil.getConnection();
PreparedStatement pstmt=null;
ResultSet rs=null;
List<EchartsBean> list=new ArrayList<>();
try {
pstmt= conn.prepareStatement(sql);
rs= pstmt.executeQuery();
while (rs.next()) {
String address = rs.getString(1);
int count = rs.getInt(2);
EchartsBean echarts=new EchartsBean(address,count);
list.add(echarts);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(rs,pstmt,conn);
}
return list;
}
service层:
StudentService:
public List<EchartsBean> findCountByAddress();
StudentServiceImpl:
@Override
public List<EchartsBean> findCountByAddress(){
return studentDao.findCountByAddress();
}
servlet:
CountServlet:
package com.jishou.servlet;
import com.alibaba.fastjson.JSONObject;
import com.jishou.pojo.EchartsBean;
import com.jishou.service.StudentService;
import com.jishou.service.StudentServiceImpl;
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;
import java.util.Map;
@WebServlet(name = "CountServlet",urlPatterns = "/count")
public class CountServlet extends HttpServlet {
private StudentService studentService=new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<EchartsBean> list = studentService.findCountByAddress();
//将List集合转换成json数据
String json = JSONObject.toJSONString(list);
req.setAttribute("list",json);
req.getRequestDispatcher("tubiao.jsp").forward(req,resp);
}
}
left.jsp 左边菜单页面添加菜单–统计模块:
注意: 超链接的指向
<a href="count" target="main">区域统计</a>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<div>
<a href="#" target="main">首页</a>
<dl>
<dt>
学生管理
</dt>
<dd>
<a href="listpage" target="main">学生列表</a>
</dd>
<dd>
<a href="add.jsp" target="main">添加学生</a>
</dd>
</dl>
<dl>
<dt>
教师管理
</dt>
<dd>
<a href="listteas" target="main">教师列表</a>
</dd>
<dd>
<a href="" target="main">添加教师</a>
</dd>
</dl>
<dl>
<dt>
班级管理
</dt>
<dd>
<a href="" target="main">班级列表</a>
</dd>
<dd>
<a href="" target="main">添加班级</a>
</dd>
</dl>
<dl>
<dt>
统计模块
</dt>
<dd>
<a href="count" target="main">区域统计</a>
</dd>
</dl>
<dl>
<dt>
系统管理
</dt>
<dd>
<a href="" target="main">修改密码</a>
</dd>
<dd>
<a href="logout" target="_parent">退出系统</a>
</dd>
</dl>
</div>
</body>
</html>
点击区域统计菜单,进入CountServlet,最终效果如下: 动态的
eg18: 连表查询一对一查询所有
-
数据库设计
设计tea老师表和clazz班级表
tea表字段:
int id 主键自增 varchar tname 教师姓名 int age 年龄
varchar subject 授课科目 int cid 班级id 管理班级表主键
clazz班级表字段:
int id 主键 自增 varchar cname 班级名称
-
实体类
教室和班级一对一关系,写Teacher属性的时候直接把Clazz clazz; 班级对象作为Teacher的属性
Clazz:
package com.jishou.pojo; public class Clazz { private int id; private String className; public Clazz() { } public Clazz(int id, String className) { this.id = id; this.className = className; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public String toString() { return "Clazz{" + "id=" + id + ", className='" + className + '\'' + '}'; } }
Teacher:
package com.jishou.pojo; public class Teacher { private int id; private String teaName; private int age; private String subject; private Clazz clazz;//一对一 一个老师带一个班级 public Teacher() { } public Teacher(int id, String teaName, int age, String subject, Clazz clazz) { this.id = id; this.teaName = teaName; this.age = age; this.subject = subject; this.clazz = clazz; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTeaName() { return teaName; } public void setTeaName(String teaName) { this.teaName = teaName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public Clazz getClazz() { return clazz; } public void setClazz(Clazz clazz) { this.clazz = clazz; } @Override public String toString() { return "Teacher{" + "id=" + id + ", teaName='" + teaName + '\'' + ", age=" + age + ", subject='" + subject + '\'' + ", clazz=" + clazz + '}'; } }
-
dao层
TeacherDao:
package com.jishou.dao; import com.jishou.pojo.Teacher; import java.util.List; public interface TeacherDao { public List<Teacher> queryAllTeachers(); }
TeacherDaoImpl:
package com.jishou.dao; import com.jishou.pojo.Clazz; import com.jishou.pojo.Student; import com.jishou.pojo.Teacher; import com.jishou.util.DBUtil; import java.sql.*; import java.util.ArrayList; import java.util.List; public class TeacherDaoImpl implements TeacherDao { @Override public List<Teacher> queryAllTeachers() { String sql="select t.id,t.tname,t.age,t.subject,c.id,c.cname FROM tea t ,clazz c where t.id=c.id"; Connection conn = DBUtil.getConnection(); List<Teacher> list = new ArrayList<>(); PreparedStatement pstmt=null; ResultSet rs=null; try { pstmt= conn.prepareStatement(sql); rs= pstmt.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String tname = rs.getString(2); int age = rs.getInt(3); String subject = rs.getString(4); int cid = rs.getInt(5); String cname = rs.getString(6); Clazz clazz=new Clazz(cid,cname); Teacher teacher=new Teacher(id,tname,age,subject,clazz); list.add(teacher); } }catch (SQLException e){ e.printStackTrace(); }finally { DBUtil.close(rs,pstmt,conn); } return list; } }
-
service层
TeacherService:
package com.jishou.service; import com.jishou.pojo.Teacher; import java.util.List; public interface TeacherService { public List<Teacher> queryAllTeachers(); }
TeacherServiceImpl:
package com.jishou.service; import com.jishou.dao.TeacherDao; import com.jishou.dao.TeacherDaoImpl; import com.jishou.pojo.Teacher; import java.util.List; public class TeacherServiceImpl implements TeacherService { private TeacherDao teacherDao=new TeacherDaoImpl(); @Override public List<Teacher> queryAllTeachers() { return teacherDao.queryAllTeachers(); } }
-
servlet
ListTeasServlet:
package com.jishou.servlet; import com.jishou.pojo.Teacher; import com.jishou.service.TeacherService; import com.jishou.service.TeacherServiceImpl; 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(name = "ListTeasServlet",urlPatterns = "/listteas") public class ListTeasServlet extends HttpServlet { private TeacherService teacherService=new TeacherServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Teacher> teachers = teacherService.queryAllTeachers(); req.setAttribute("list",teachers); req.getRequestDispatcher("tealist.jsp").forward(req,resp); } }
-
前端页面
tealist.jsp:
<%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>Title</title> </head> <body> <center> <h1>教师管理系统</h1> <table width="70%" height="50%"> <tr> <td>Id</td> <td>姓名</td> <td>年龄</td> <td>授课科目</td> <td>所带班级</td> </tr> <c:if test="${list ne null and list.size() gt 0}"> <c:forEach var="t" items="${list}"> <tr> <td>${t.id}</td> <td>${t.teaName}</td> <td>${t.age}</td> <td>${t.subject}</td> <td>${t.clazz.className}</td> </tr> </c:forEach> </c:if> </table> </center> </body> </html>
7.效果 点击左边 教师列表 超链接
eg19: 实现角色权限管理
角色权限管理
3个概念:
用户 :当前登录系统的用户
角色 :某个用户具备的角色 管理员或者普通会员
权限: 所拥有的资源 ,表现为所能操作的菜单的多少
关系:
用户和角色 一对一 角色和菜单 多对多
一个用户一个角色, 一个角色多个权限
不同的用户不同的角色,不同的角色不同的权限;所以每个用户登录之后显示的权限菜单不一样
流程:
用户正常登录进入系统, 由于不同用户不同角色不同的权限大小,登录之后必须权限查询,在列表上展现出来
登录页面--》 login后台-----》登录成功之后 获取roleId----->再根据roleId查询出对应的权限信息
表的设计:
3张主表
user role menu ,
2张中间表 user_role role_menu
主表:
user: id username password
role: roleid rolename
menu: id name url target pid
中间表:
user_role: uid rid
role_menu: rid mid
实体类设计:
3个实体类:
User:
Integer id;
String username;
String password;
Role role;
Role:
Integer roleId;
String roleName
Menu:
int id;
String name;
String url;
String target;
int pid;
实现流程:
1. login.jsp
```form表单登录 到后台login
2. servletlogin登录的后台逻辑实现登录
sql: 3表联查 查询出来的user里面会有role信息,包括roleId
再根据roleId查询出对应的权限信息;
吧登录成功的User对象和List
跳转到index.jsp中
4. left.jsp 左边菜单列表通过循环遍历显示出来
<ul>
<c:forEach var="m" items="${menus}">
<li>
<a href="${m.url}" target="${m.target}">${m.name}</a>
</li>
</c:forEach>
</ul>
步骤:
-
login.jsp 登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>登录页面</h1> <!--前端访问路径都不加/ --> <form action="login" method="post"> 用户名: <input type="text" name="username"><br> 密码: <input type="password" name="password"><br> <input type="submit" value="登录"> <a href="register.jsp">立即注册</a> </form> </body> </html>
-
实体类pojo
User:
package com.jishou.pojo; public class User { private int id; private String username; private String password; private Role role; public User() { } public User(String username, String password) { this.username = username; this.password = password; } public User(int id, String username, String password, Role role) { this.id = id; this.username = username; this.password = password; this.role = role; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", role=" + role + '}'; } }
Role:
package com.jishou.pojo; public class Role { private int roleId; private String roleName; public Role() { } public Role(int roleId, String roleName) { this.roleId = roleId; this.roleName = roleName; } public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } @Override public String toString() { return "Role{" + "roleId=" + roleId + ", roleName='" + roleName + '\'' + '}'; } }
Menu:
package com.jishou.pojo; public class Menu { private int id; private String name; private String url; private String target; private int pid; public Menu() { } public Menu(int id, String name, String url, String target, int pid) { this.id = id; this.name = name; this.url = url; this.target = target; this.pid = pid; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } @Override public String toString() { return "Menu{" + "id=" + id + ", name='" + name + '\'' + ", url='" + url + '\'' + ", target='" + target + '\'' + ", pid=" + pid + '}'; } }
-
dao层
UserDao:
package com.jishou.dao; import com.jishou.pojo.Menu; import com.jishou.pojo.User; import java.util.List; public interface UserDao { public User queryOneUser(User user); public List<Menu> queryMenusByRoleId(int roleId); }
UserDaoImpl:
package com.jishou.dao; import com.jishou.pojo.Menu; import com.jishou.pojo.Role; import com.jishou.pojo.User; import com.jishou.util.DBUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class UserDaoImpl implements UserDao{ @Override public User queryOneUser(User user) { String sql="select u.id,u.username,u.`password` ,r.roleid,r.rolename from user u,user_role ur ,role r where u.id=ur.uid and ur.rid=r.roleid and u.username=? and u.password=?"; PreparedStatement pstmt=null; ResultSet rs=null; //2. 获取连接 修路 Connection conn = DBUtil.getConnection(); User u=null; try { //3. 创建PreparedStatement 造车 pstmt = conn.prepareStatement(sql); pstmt.setString(1,user.getUsername()); pstmt.setString(2,user.getPassword()); //4. 执行sql 拉货 rs = pstmt.executeQuery(); //5. 处理结果集 查询会有结果集 处理货物 if (rs.next()) { int id = rs.getInt(1); String username = rs.getString(2); String password = rs.getString(3); int roleid = rs.getInt(4); String rolename = rs.getString(5); Role role=new Role(roleid,rolename); u=new User(id,username,password,role); } }catch (SQLException e){ e.printStackTrace(); }finally { //6. 关闭资源 货 车 路全都毁了 DBUtil.close(rs,pstmt,conn); } return u; } @Override public List<Menu> queryMenusByRoleId(int roleId) { String sql="select m.* from role_menu rm ,menu m where rm.mid=m.id and rm.rid=?"; PreparedStatement pstmt=null; ResultSet rs=null; List<Menu> list=new ArrayList<>(); //2. 获取连接 修路 Connection conn = DBUtil.getConnection(); try { //3. 创建PreparedStatement 造车 pstmt = conn.prepareStatement(sql); pstmt.setInt(1,roleId); //4. 执行sql 拉货 rs = pstmt.executeQuery(); //5. 处理结果集 查询会有结果集 处理货物 while (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); String url = rs.getString(3); String target = rs.getString(4); int pid = rs.getInt(5); Menu menu=new Menu(id,name,url,target,pid); list.add(menu); } }catch (SQLException e){ e.printStackTrace(); }finally { //6. 关闭资源 货 车 路全都毁了 DBUtil.close(rs,pstmt,conn); } return list; } }
-
service层
UserService:
package com.jishou.service; import com.jishou.pojo.Menu; import com.jishou.pojo.User; import java.util.List; public interface UserService { public User queryOneUser(User user); public List<Menu> queryMenusByRoleId(int roleId); }
UserServiceImpl:
package com.jishou.service; import com.jishou.dao.UserDao; import com.jishou.dao.UserDaoImpl; import com.jishou.pojo.Menu; import com.jishou.pojo.User; import java.util.List; public class UserServiceImpl implements UserService { private UserDao userDao=new UserDaoImpl(); @Override public User queryOneUser(User user) { return userDao.queryOneUser(user); } @Override public List<Menu> queryMenusByRoleId(int roleId) { return userDao.queryMenusByRoleId(roleId); } }
-
servlet
LoginServlet:
package com.jishou.servlet; import com.jishou.dao.UserDao; import com.jishou.dao.UserDaoImpl; import com.jishou.pojo.Menu; import com.jishou.pojo.User; 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 javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; @WebServlet(name = "LoginServlet",urlPatterns = "/login") public class LoginServlet extends HttpServlet { private UserDao userDao=new UserDaoImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); User user=new User(username,password); User htUser = userDao.queryOneUser(user); if(htUser!=null){ //登录成功 //再根据roleId来查询权限信息 int roleId = htUser.getRole().getRoleId(); List<Menu> menus = userDao.queryMenusByRoleId(roleId); //放到session对象中 HttpSession session = req.getSession(); session.setAttribute("user",htUser); session.setAttribute("menus",menus); //跳转到首页 resp.sendRedirect("index.jsp"); }else{ resp.sendRedirect("login.jsp"); } } }
-
前端left.jsp渲染菜单
index.jsp为frameset,3个网页的集合
left.jsp
<%-- Created by IntelliJ IDEA. User: mumusan Date: 2021/6/2 Time: 16:20 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <div> <ul> <c:forEach var="m" items="${menus}"> <li> <a href="${m.url}" target="${m.target}">${m.name}</a> </li> </c:forEach> </ul> </div> </body> </html>
访问测试;使用不同的用户访问登录测试
eg20: 使用maven创建工程
-
下载maven压缩包
apache-maven-3.6.0-bin.zip
-
解压压缩包,在conf/setting.xml配置阿里云中央仓库
注意: 不要解压在中文路径下
在conf/setting.xml配置 本地仓库路径和阿里云中央仓库
<localRepository>D:\soft\repository</localRepository>
<!-- 阿里云仓库 --> <mirror> <id>alimaven</id> <mirrorOf>central</mirrorOf> <name>aliyun maven</name> <url>https://maven.aliyun.com/repository/central</url> </mirror>
-
idea里面关联maven
setting------maven----配置maven home 和 User setting file
New Project Settings—Settings For New Projects…也需要同样配置
-
创建maven web工程
new project----maven project
- 完善目录结构
-
pom.xml文件里面添加依赖
注意: pom.xml里面自动生成的这些东西可以删除
<name>maven0100 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>maven0100</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build>
完整的pom文件,添加web依赖后的工程
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jishou</groupId> <artifactId>maven0100</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- JSP --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- JSTL --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <!-- 配置Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8082</port> <path>/</path> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
依赖添加完毕后记得更新maven依赖
右边菜单 maven -------左上方 刷新图标 点击
-
编写代码
src/main/java
底下创建一个Servlet
package com.jihsou.servlet; 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; @WebServlet(name = "HelloServlet",urlPatterns = "/hello") public class HelloServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("index.jsp"); } }
index.jsp
内容为hello worldd
-
启动运行tomcat服务器 :
这里使用maven-tomcat插件
右面M 图标 点击 输入 tomcat7:run 即可启动
浏览器访问:http://localhost:8082/hello