Cookie和Session

关于用Cookie和Session改进项目代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie productId = new Cookie("pw", "math");
productId.setMaxAge(60*60);
productId.setPath("/cookie");//在cookie路径和其中子路径
response.addCookie(productId);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.xiaoguan.oa.dept.web;

import com.xiaoguan.oa.dept.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/login","/logout"})
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String servletPath = request.getServletPath();
if("/login".equals(servletPath)){
doLogin(request,response);
} else if ("/logout".equals(servletPath)) {
doLogout(request,response);
} else{
System.out.println("用户Servlet操作错误");
}
}

private void doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if(session!=null){
session.invalidate();
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
}

protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
boolean flag=false;
int id=0;
try {
conn= DBUtil.getConnection();
String sql="select id from login where 登录名=? and 登录密码=?";
ps=conn.prepareStatement(sql);
ps.setString(1,userName);
ps.setString(2,userPassword);
rs=ps.executeQuery();
if(rs.next()){
flag=true;
id=rs.getInt("id");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
if(flag){
HttpSession session = request.getSession();
session.setAttribute("id",id);
session.setAttribute("userName",userName);
if("1".equals(request.getParameter("flag")))
{
Cookie userNameLoginCookie = new Cookie("userName", userName);
Cookie userPasswordLoginCookie = new Cookie("userPassword", userPassword);
userNameLoginCookie.setMaxAge(60*60*24*10);
userPasswordLoginCookie.setMaxAge(60*60*24*10);
userNameLoginCookie.setPath(request.getContextPath());
userPasswordLoginCookie.setPath(request.getContextPath());
response.addCookie(userNameLoginCookie);
response.addCookie(userPasswordLoginCookie);
}
response.sendRedirect(request.getContextPath()+"/list");
}else{
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.xiaoguan.oa.dept.web;

import com.xiaoguan.oa.dept.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
String userPassword=null;
String userName=null;
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
if("userName".equals(name)){
userName = cookie.getValue();
}
if("userPassword".equals(name)){
userPassword = cookie.getValue();
}
}
}
if(userName!=null&&userPassword!=null){
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
boolean flag=false;
int id=0;
try {
conn= DBUtil.getConnection();
String sql="select id from login where 登录名=? and 登录密码=?";
ps=conn.prepareStatement(sql);
ps.setString(1,userName);
ps.setString(2,userPassword);
rs=ps.executeQuery();
if(rs.next()){
flag=true;
id=rs.getInt("id");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
if(flag) {
HttpSession session = request.getSession();
session.setAttribute("id", id);
session.setAttribute("userName", userName);
response.sendRedirect(request.getContextPath() + "/list");
}else {
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
}else{
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package com.xiaoguan.oa.dept.web;

import com.xiaoguan.oa.dept.bean.Dept;
import com.xiaoguan.oa.dept.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/list","/detail","/delete","/add","/modify"})
public class DeptServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if(session!=null&&session.getAttribute("id")!=null){
String servletPath = request.getServletPath();
if("/list".equals(servletPath)){
doList(request,response);
} else if ("/detail".equals(servletPath)) {
doDetail(request,response);
} else if ("/delete".equals(servletPath)) {
doDel(request,response);
} else if ("/add".equals(servletPath)) {
doAdd(request,response);

} else if ("/modify".equals(servletPath)) {
doModify(request,response);
} else {
System.out.println("路径有误!");
}
} else {
response.sendRedirect(request.getContextPath()+"/welcome");
}
}

private void doModify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String deptno = request.getParameter("deptno");
String dname = request.getParameter("dname");
String loc = request.getParameter("loc");
Connection conn=null;
PreparedStatement ps=null;
int count=0;
try {
conn= DBUtil.getConnection();
String sql="update dept set dname=?,loc=? where deptno=?";
ps=conn.prepareStatement(sql);
ps.setString(3,deptno);
ps.setString(1,dname);
ps.setString(2,loc);
count=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,null);
}
if(count==1){
response.sendRedirect(request.getContextPath()+"/list");
}else {
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}

private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String deptno = request.getParameter("deptno");
String dname = request.getParameter("dname");
String loc = request.getParameter("loc");
Connection conn=null;
PreparedStatement ps=null;
int count=0;
try {
conn= DBUtil.getConnection();
String sql="insert into dept(deptno,dname,loc) values(?,?,?)";
ps=conn.prepareStatement(sql);
ps.setString(1,deptno);
ps.setString(2,dname);
ps.setString(3,loc);
count=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,null);
}
if(count==1){
response.sendRedirect(request.getContextPath()+"/list");
}else {
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}

private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String deptno = request.getParameter("deptno");
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
int count=0;
try {
conn=DBUtil.getConnection();
String sql="delete from dept where deptno=?";
ps=conn.prepareStatement(sql);
ps.setString(1,deptno);
count=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
if(count==1){
response.sendRedirect(request.getContextPath()+"/list");
}else {
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}

private void doDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String deptno = request.getParameter("deptno");
String flag = request.getParameter("f");
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
Dept dept=null;
try {
conn=DBUtil.getConnection();
String sql="select dname,loc from dept where deptno=?";
ps=conn.prepareStatement(sql);
ps.setString(1,deptno);
rs=ps.executeQuery();
if(rs.next()){
String dname = rs.getString("dname");
String loc = rs.getString("loc");
dept=new Dept(deptno,dname,loc);
request.setAttribute("dept",dept);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
if("d".equals(flag)){
request.getRequestDispatcher("/detail.jsp").forward(request,response);
} else if ("m".equals(flag)) {
request.getRequestDispatcher("/edit.jsp").forward(request,response);
}else {
System.out.println("f传参参数有误!");
}

}

private void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Dept> depts = new ArrayList<>();
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn=DBUtil.getConnection();
String sql="select deptno,dname,loc from dept";
ps= conn.prepareStatement(sql);
rs=ps.executeQuery();
while (rs.next()) {
String deptno=rs.getString("deptno");
String dname = rs.getString("dname");
String loc=rs.getString("loc");
Dept dept=new Dept(deptno,dname,loc);
depts.add(dept);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
request.setAttribute("deptList",depts);
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
}

在XML里设置session存在时间代码

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0">
<!--session超时时长为30分钟-->
<welcome-file-list>
<welcome-file>/welcome</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>