本文主要為大家分析了圖書商城的用戶模塊,具體內(nèi)容如下
1、用戶模塊的相關(guān)類創(chuàng)建
domain:User
dao:UserDao
service:UserDao
web.servlet:UserServlet
2、用戶注冊
2.1 注冊流程
/jsps/user/regist.jsp -> UserServlet#regist() -> msg.jsp
2.2 注冊頁面
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
|
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html > < head > < title >注冊</ title > < meta http-equiv = "pragma" content = "no-cache" > < meta http-equiv = "cache-control" content = "no-cache" > < meta http-equiv = "expires" content = "0" > < meta http-equiv = "keywords" content = "keyword1,keyword2,keyword3" > < meta http-equiv = "description" content = "This is my page" > < meta http-equiv = "content-type" content = "text/html;charset=utf-8" > <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </ head > < body > < h1 >注冊</ h1 > <%-- 1. 顯示errors --> 字段錯(cuò)誤 2. 顯示異常錯(cuò)誤 3. 回顯 --%> < p style = "color: red; font-weight: 900" >${msg }</ p > < form action="<c:url value = '/UserServlet' />" method="post"> < input type = "hidden" name = "method" value = "regist" /> 用戶名:< input type = "text" name = "username" value = "${form.username }" /> < span style = "color: red; font-weight: 900" >${errors.username }</ span > < br /> 密 碼:< input type = "password" name = "password" value = "${form.password }" /> < span style = "color: red; font-weight: 900" >${errors.password }</ span > < br /> 郵 箱:< input type = "text" name = "email" value = "${form.email }" /> < span style = "color: red; font-weight: 900" >${errors.email }</ span > < br /> < input type = "submit" value = "注冊" /> </ form > </ body > </ html > |
2.3 UserServlet
User
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * User的領(lǐng)域?qū)ο?/code> */ public class User { /* * 對應(yīng)數(shù)據(jù)庫表 */ private String uid; // 主鍵 private String username; // 用戶名 private String password; // 密碼 private String email; // 郵箱 private String code; // 激活碼 private boolean state; // 狀態(tài)(已激活和未激活) |
BaseServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class BaseServlet extends HttpServlet { /* * 它會(huì)根據(jù)請求中的method,來決定調(diào)用本類的哪個(gè)方法 */ protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding( "UTF-8" ); res.setContentType( "text/html;charset=utf-8" ); try { // 例如:http://localhost:8080/demo1/xxx?m=add String method = req.getParameter( "method" ); // 它是一個(gè)方法名稱 Class c = this .getClass(); Method m = c.getMethod(method, HttpServletRequest. class , HttpServletResponse. class ); String result = (String) m.invoke( this , req, res); if (result != null && !result.isEmpty()) { req.getRequestDispatcher(result).forward(req, res); } } catch (Exception e) { throw new ServletException(e); } } } |
UserServlet
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
|
/** * User表述層 */ public class UserServlet extends BaseServlet { private UserService userService = new UserService(); /** * 退出功能 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String quit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().invalidate(); return "r:/index.jsp" ; } public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. 封裝表單數(shù)據(jù)到form中 * 2. 輸入校驗(yàn)(不寫了) * 3. 調(diào)用service完成激活 * > 保存錯(cuò)誤信息、form到request,轉(zhuǎn)發(fā)到login.jsp * 4. 保存用戶信息到session中,然后重定向到index.jsp */ User form = CommonUtils.toBean(request.getParameterMap(), User.class); try { User user = userService.login(form); request.getSession().setAttribute("session_user", user); /* * 給用戶添加一個(gè)購物車,即向session中保存一Cart對象 */ request.getSession().setAttribute("cart", new Cart()); return "r:/index.jsp"; } catch (UserException e) { request.setAttribute("msg", e.getMessage()); request.setAttribute("form", form); return "f:/jsps/user/login.jsp"; } } /** * 激活功能 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. 獲取參數(shù)激活碼 * 2. 調(diào)用service方法完成激活 * > 保存異常信息到request域,轉(zhuǎn)發(fā)到msg.jsp * 3. 保存成功信息到request域,轉(zhuǎn)發(fā)到msg.jsp */ String code = request.getParameter("code"); try { userService.active(code); request.setAttribute("msg", "恭喜,您激活成功了!請馬上登錄!"); } catch (UserException e) { request.setAttribute("msg", e.getMessage()); } return "f:/jsps/msg.jsp"; } /** * 注冊功能 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. 封裝表單數(shù)據(jù)到form對象中 * 2. 補(bǔ)全:uid、code * 3. 輸入校驗(yàn) * > 保存錯(cuò)誤信息、form到request域,轉(zhuǎn)發(fā)到regist.jsp * 4. 調(diào)用service方法完成注冊 * > 保存錯(cuò)誤信息、form到request域,轉(zhuǎn)發(fā)到regist.jsp * 5. 發(fā)郵件 * 6. 保存成功信息轉(zhuǎn)發(fā)到msg.jsp */ // 封裝表單數(shù)據(jù) User form = CommonUtils.toBean(request.getParameterMap(), User.class); // 補(bǔ)全 form.setUid(CommonUtils.uuid()); form.setCode(CommonUtils.uuid() + CommonUtils.uuid()); /* * 輸入校驗(yàn) * 1. 創(chuàng)建一個(gè)Map,用來封裝錯(cuò)誤信息,其中key為表單字段名稱,值為錯(cuò)誤信息 */ Map<String,String> errors = new HashMap<String,String>(); /* * 2. 獲取form中的username、password、email進(jìn)行校驗(yàn) */ String username = form.getUsername(); if(username == null || username.trim().isEmpty()) { errors.put("username", "用戶名不能為空!"); } else if(username.length() < 3 || username.length() > 10) { errors.put("username", "用戶名長度必須在3~10之間!"); } String password = form.getPassword(); if(password == null || password.trim().isEmpty()) { errors.put("password", "密碼不能為空!"); } else if(password.length() < 3 || password.length() > 10) { errors.put("password", "密碼長度必須在3~10之間!"); } String email = form.getEmail(); if(email == null || email.trim().isEmpty()) { errors.put("email", "Email不能為空!"); } else if(!email.matches("\\w+@\\w+\\.\\w+")) { errors.put("email", "Email格式錯(cuò)誤!"); } /* * 3. 判斷是否存在錯(cuò)誤信息 */ if(errors.size() > 0) { // 1. 保存錯(cuò)誤信息 // 2. 保存表單數(shù)據(jù) // 3. 轉(zhuǎn)發(fā)到regist.jsp request.setAttribute("errors", errors); request.setAttribute("form", form); return "f:/jsps/user/regist.jsp"; } /* * 調(diào)用service的regist()方法 */ try { userService.regist(form); } catch (UserException e) { /* * 1. 保存異常信息 * 2. 保存form * 3. 轉(zhuǎn)發(fā)到regist.jsp */ request.setAttribute("msg", e.getMessage()); request.setAttribute("form", form); return "f:/jsps/user/regist.jsp"; } /* * 發(fā)郵件 * 準(zhǔn)備配置文件! */ // 獲取配置文件內(nèi)容 Properties props = new Properties(); props.load(this.getClass().getClassLoader() .getResourceAsStream("email_template.properties")); String host = props.getProperty("host");//獲取服務(wù)器主機(jī) String uname = props.getProperty("uname");//獲取用戶名 String pwd = props.getProperty("pwd");//獲取密碼 String from = props.getProperty("from");//獲取發(fā)件人 String to = form.getEmail();//獲取收件人 String subject = props.getProperty("subject");//獲取主題 String content = props.getProperty("content");//獲取郵件內(nèi)容 content = MessageFormat.format(content, form.getCode());//替換{0} Session session = MailUtils.createSession(host, uname, pwd);//得到session Mail mail = new Mail(from, to, subject, content);//創(chuàng)建郵件對象 try { MailUtils.send(session, mail);//發(fā)郵件! } catch (MessagingException e) { } /* * 1. 保存成功信息 * 2. 轉(zhuǎn)發(fā)到msg.jsp */ request.setAttribute( "msg" , "恭喜,注冊成功!請馬上到郵箱激活" ); return "f:/jsps/msg.jsp" ; } } |
2.4 UserService
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
|
/** * User業(yè)務(wù)層 */ public class UserService { private UserDao userDao = new UserDao(); /** * 注冊功能 * @param form */ public void regist(User form) throws UserException{ // 校驗(yàn)用戶名 User user = userDao.findByUsername(form.getUsername()); if (user != null ) throw new UserException( "用戶名已被注冊!" ); // 校驗(yàn)email user = userDao.findByEmail(form.getEmail()); if (user != null ) throw new UserException( "Email已被注冊!" ); // 插入用戶到數(shù)據(jù)庫 userDao.add(form); } /** * 激活功能 * @throws UserException */ public void active(String code) throws UserException { /* * 1. 使用code查詢數(shù)據(jù)庫,得到user */ User user = userDao.findByCode(code); /* * 2. 如果user不存在,說明激活碼錯(cuò)誤 */ if(user == null) throw new UserException("激活碼無效!"); /* * 3. 校驗(yàn)用戶的狀態(tài)是否為未激活狀態(tài),如果已激活,說明是二次激活,拋出異常 */ if(user.isState()) throw new UserException("您已經(jīng)激活過了,不要再激活了,除非你想死!"); /* * 4. 修改用戶的狀態(tài) */ userDao.updateState(user.getUid(), true); } /** * 登錄功能 * @param form * @return * @throws UserException */ public User login(User form) throws UserException { /* * 1. 使用username查詢,得到User * 2. 如果user為null,拋出異常(用戶名不存在) * 3. 比較form和user的密碼,若不同,拋出異常(密碼錯(cuò)誤) * 4. 查看用戶的狀態(tài),若為false,拋出異常(尚未激活) * 5. 返回user */ User user = userDao.findByUsername(form.getUsername()); if (user == null ) throw new UserException( "用戶名不存在!" ); if (!user.getPassword().equals(form.getPassword())) throw new UserException( "密碼錯(cuò)誤!" ); if (!user.isState()) throw new UserException( "尚未激活!" ); return user; } } |
2.5 UserDao
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
|
/** * User持久層 */ public class UserDao { private QueryRunner qr = new TxQueryRunner(); /** * 按用戶名查詢 * @param username * @return */ public User findByUsername(String username) { try { String sql = "select * from tb_user where username=?" ; return qr.query(sql, new BeanHandler<User>(User. class ), username); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 按email查詢 * @param email * @return */ public User findByEmail(String email) { try { String sql = "select * from tb_user where email=?" ; return qr.query(sql, new BeanHandler<User>(User. class ), email); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 插入U(xiǎn)ser * @param user */ public void add(User user) { try { String sql = "insert into tb_user values(?,?,?,?,?,?)" ; Object[] params = {user.getUid(), user.getUsername(), user.getPassword(), user.getEmail(), user.getCode(), user.isState()}; qr.update(sql, params); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 按激活碼查詢 * @param code * @return */ public User findByCode(String code) { try { String sql = "select * from tb_user where code=?" ; return qr.query(sql, new BeanHandler<User>(User. class ), code); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 修改指定用戶的指定狀態(tài) * @param uid * @param state */ public void updateState(String uid, boolean state) { try { String sql = "update tb_user set state=? where uid=?" ; qr.update(sql, state, uid); } catch (SQLException e) { throw new RuntimeException(e); } } } |
3、用戶激活
流程:用戶的郵件中 -> UserServlet#active() -> msg.jsp
用戶登錄
流程:/jsps/user/login.jsp -> UserServlet#login() -> index.jsp
用戶退出
流程:top.jsp -> UserServlet#quit() -> login.jsp
quit():把session銷毀!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。