hooyantsing's Blog

第72次课程_MVC模式[廖彦]

字数统计: 6.2k阅读时长: 29 min
2019/10/27

源辰76班

第72次课程

2019.10.27

内容

MVC模式[廖彦]

1.MVC模式特征

**b66f6c8ae6b20eeed72db471e34cce18.png

**

创建四个包

bean :对象,容器类

biz : 逻辑判断的代码

dao : 操作数据库的代码

servlet:业务服务

2.案例

[对现有大麦(damai)电商项目代码进行改造,使其按照MVC模式进行开发]

项目结构图:

f7fd752f1c07b243c02cdde0666fd81c.png

reg.jsp

大麦(damai)电商项目的注册页面。

代码改造(紫色标记):将Ajax技术的URL链接到servlet上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=UTF-8" />
<title>大麦商城</title>
<link href="css/common.css"
    rel="stylesheet" type="text/css" />
<link href="css/register.css"
    rel="stylesheet" type="text/css" />
<script type="text/javascript"
    src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
    function checkForm(){
       // 校验用户名:
       
       // 校验密码:
       
       // 校验确认密码
       
       //校验邮箱
       return false;
    }
    
    var xmlhttp;
    // ajax 验证用户名是否存在
    try {
       xmlhttp = new  ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
       try {
           xmlhttp = new  ActiveXObject("Microsoft.XMLHTTP");
       } catch (e) {
           try {
               xmlhttp = new  XMLHttpRequest();
           } catch (e) {
           }
       }
    }
    //校验用户名是否存在
    function checkUserName(){
       
       // 获取用户填写的用户名
       var name =  document.getElementById("username").value;
       
       name = name.replace(/\s/gi,"");
       if(name == ''){
           alert("请填写用户名!");
           return;
       }
       
       if(xmlhttp!=null){
           // 定义请求地址
           var url  ="doCheckUsername.jsp?username="+name;
                  
           // 以 POST 方式 开启连接
           // POST 请求 更安全(编码)  提交的数据大小没有限制
           xmlhttp.open("POST",url,true);
           
           // 设置回调函数   // 当收到服务器的响应时,会触发该函数(回调函数)
           // 每次的状态改变都会调用该方法
           xmlhttp.onreadystatechange=function(){
               if(xmlhttp.readyState == 4 &&  xmlhttp.status == 200){
                  // 替换空格
                  var msg =  xmlhttp.responseText.replace(/\s/gi,"");
                  // 使用 span 展示错误信息,  替代 alert(msg); 提升用户体验
                  // 允许注册使用绿色字体,  否则红色字体
                  var color = msg == '该用户名可以注册!' ? 'green' : 'red';
                  // 输入框的后面一个元素是用于展示信息的 span 元素
                  $("#username").next().text(msg).css("color",  color);  
               }
           };
           // 发送请求
           xmlhttp.send(null);
       }else{
           alert("不能创建XMLHttpRequest对象实例")
       }
    }
    function changeImg(){
       // 更新验证码
    }
    
    function reg(){
       var username =  document.getElementById("username").value;
       var password =  document.getElementById("password").value;
       var repassword =  document.getElementById("repassword").value;
       var email = document.getElementById("email").value;
       var phone =  document.getElementById("phone").value;
       var name = $("#name").val();  // 使用 jquery 选择器搞定!!!
       var sex =  $("input[name='sex']:checked").val(); //  checked选择器写法记错了,已修改
       
       if(xmlhttp!=null){
           // 定义请求地址
           var url =  "user.s?op=reg&username="+username
                  + "&password=" + password
                  + "&repassword=" +  repassword
                  + "&email=" + email
                  + "&phone=" + phone
                  + "&sex=" + sex;
           // 以 POST 方式 开启连接
           // POST 请求 更安全(编码)  提交的数据大小没有限制
           xmlhttp.open("POST",url,true);
           
           // 设置回调函数   // 当收到服务器的响应时,会触发该函数(回调函数)
           // 每次的状态改变都会调用该方法
           xmlhttp.onreadystatechange=function(){
               if(xmlhttp.readyState == 4 &&  xmlhttp.status == 200){
                  var json =  xmlhttp.responseText.replace(/\s/gi,"");
                  eval("var result = " +  json);
                  console.info(result);
                  if(result.code==1){
                      alert(result.msg);
                      //成功 js跳转
                      location.href =  "login.jsp";
                  } else {
                      alert(result.msg);
                  }
               }
           };
           // 发送请求
           xmlhttp.send(null);
       }else{
           alert("不能创建XMLHttpRequest对象实例")
       }
       
       
    }
    </script>
</head>
<body>
    <div class="container header">
       
<div class="span5">
       <div class="logo">
           <a href="index.jsp">
               <img  src="image/r___________renleipic_01/logo.png" alt="依依不舍"/>
           </a>
       </div>
    </div>
    <div class="span9">
<div class="headerAd">
    <img src="image/header.jpg" width="320"  height="50" alt="正品保障" title="正品保障"/>
</div> </div>
<div class="span10 last">
       <div class="topNav clearfix">
           <ul>
               
               
               <li id="headerLogin"  class="headerLogin" style="display:  list-item;">
                  <a href="login.jsp">登录</a>|
               </li>
               <li id="headerRegister"  class="headerRegister" style="display:  list-item;">
                  <a href="reg.jsp">注册</a>|
               </li>
               
               
               
               <li id="headerUsername"  class="headerUsername"></li>
               <li id="headerLogout"  class="headerLogout">
                  <a  href="LogoutServlet">[退出]</a>|
               </li>
                      <li>
                          <a>会员中心</a>
                          |
                      </li>
                      <li>
                          <a>购物指南</a>
                          |
                      </li>
                      <li>
                          <a>关于我们</a>
                          
                      </li>
           </ul>
       </div>
       <div class="cart">
           <a  href="cart.jsp">购物车</a>
       </div>
           <div class="phone">
               客服热线:
               <strong>96008/53277764</strong>
           </div>
    </div>
       
<div class="span24">
       <ul class="mainNav">
                  <li>
                      <a href="index.jsp">首页</a>
                      |
                  </li>
                  
                  <li>
<a href="clist.jsp?1&pageIndex=1">
                  女装男装
</a>
                  |</li>
                  
                  <li>
<a href="clist.jsp?2&pageIndex=1">
                  鞋靴箱包
</a>
                  |</li>
                  
                  <li>
<a href="clist.jsp?3&pageIndex=1">
                  运动户外
</a>
                  |</li>
                  
                  <li>
<a href="clist.jsp?4&pageIndex=1">
                  珠宝配饰
</a>
                  |</li>
                  
                  <li>
<a href="clist.jsp?5&pageIndex=1">
                  手机数码
</a>
                  |</li>
                  
                  <li>
<a href="clist.jsp?6&pageIndex=1">
                  家电办公
</a>
                  |</li>
                  
                  <li>
<a href="clist.jsp?7&pageIndex=1">
                  护肤彩妆
</a>
                  |</li>
                          
       </ul>
    </div>
    </div>
    <div class="container register">
       <div class="span24">
           <div class="wrap">
               <div class="main clearfix">
                  <div class="title">
                      <strong>会员注册</strong>USER REGISTER
                  </div>
                  <form id="registerForm"
                      action="reg.jsp"
                      method="post"  novalidate="novalidate"
                      onsubmit="reg();  return false;">
                      <table>
                          <tbody>
                              <tr>
                                 <th><span  class="requiredField">*</span>用户名:</th>
                                 <td><input  type="text" id="username" name="username"
                                     class="text" maxlength="20"  onblur="checkUserName()" />
                                     <span  id="span1"></span>
                                 </td>
                              </tr>
                              <tr>
                                 <th><span  class="requiredField">*</span>密&nbsp;&nbsp;码:</th>
                                 <td><input  type="password" id="password"  name="password"
                                     class="text" maxlength="20"  autocomplete="off" /><span>
                                 </span></td>
                              </tr>
                              <tr>
                                 <th><span  class="requiredField">*</span>确认密码:</th>
                                 <td><input  type="password" id="repassword"
                                     name="repassword" class="text"  maxlength="20"
                                     autocomplete="off" /></td>
                              </tr>
                              <tr>
                                 <th><span  class="requiredField">*</span>E-mail:</th>
                                 <td><input  type="text" id="email" name="email"
                                     class="text" maxlength="200" /><span>
                                 </span></td>
                              </tr>
                              <tr>
                                 <th><span  class="requiredField">*</span>电话:</th>
                                 <td><input  type="text" id="phone" name="phone"
                                     class="text" maxlength="200"  onkeyup="value=value.replace(/[^\d]/g,'')"  onafterpaste="value=value.replace(/\D/g,'')">
                                 </td>
                              </tr>
                              <tr>
                                 <th>姓名:</th>
                                 <td><input  type="text" id="name" name="name"  class="text"
                                     maxlength="200">
                                 </td>
                              </tr>
                              <tr>
                                 <th>性别:</th>
                                 <td><span  class="fieldSet"> <label> <input
                                            type="radio" name="sex" value="男">男
                                     </label> <label> <input type="radio"  name="sex" value="女">女
                                         
                                     </label> </span></td>
                              </tr>
                              <!-- <tr>
                                 <th>地址:</th>
                                 <td><input  type="text" name="address" class="text"
                                     maxlength="200">
                                 </td>
                              </tr> -->
                              <tr>
                                 <th><span  class="requiredField">*</span>验证码:</th>
                                 <td><span  class="fieldSet"> <input type="text"
                                         id="captcha" name="captcha" class="text  captcha"
                                         maxlength="4" autocomplete="off"><img
                                            id="captchaImage" class="captchaImage"
                                            src="images/vcode.jpg"
                                            title="点击更换验证码" onclick="changeImg()">
                                 </span></td>
                              </tr>
                              <tr>
                                 <th>&nbsp;</th>
                                 <td><input  type="submit" class="submit" value="同意以下协议并注册">
                                 </td>
                              </tr>
                              <tr>
                                 <th>&nbsp;</th>
                                 <td>注册协议</td>
                              </tr>
                              <tr>
                                 <th>&nbsp;</th>
                                 <td>
                                     <div  id="agreement" class="agreement"  style="height: 200px;">
                                         <p>尊敬的用户欢迎您注册成为本网站会员。请用户仔细阅读以下全部内容。如用户不同意本服务条款任意内容,请不要注册或使用本网站服务。如用户通过本网站注册程序,即表示用户与本网站已达成协议,自愿接受本服务条款的所有内容。此后,用户不得以未阅读本服务条款内容作任何形式的抗辩。</p>
                                         <p>
                                            一、本站服务条款的确认和接纳
本网站涉及的各项服务的所有权和运作权归本网站所有。本网站所提供的服务必须按照其发布的服务条款和操作规则严格执行。本服务条款的效力范围及于本网站的一切产品和服务,用户在享受本网站的任何服务时,应当受本服务条款的约束。
                                         </p>
                                         <p>
                                            二、服务简介
本网站运用自己的操作系统通过国际互联网络为用户提供各项服务。用户必须: 1.
                                                提供设备,如个人电脑、手机或其他上网设备。  2. 个人上网和支付与此服务有关的费用。
                                         </p>
                                         <p>
                                            三、用户在不得在本网站上发布下列违法信息
1.  反对宪法所确定的基本原则的; 2.
                                                危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的; 3. 损害国家荣誉和利益的; 4.
                                                煽动民族仇恨、民族歧视,破坏民族团结的; 5.  破坏国家宗教政策,宣扬邪教和封建迷信的; 6.
                                                散布谣言,扰乱社会秩序,破坏社会稳定的; 7.  散布淫秽、色情、赌博、暴力、凶杀、恐怖或者教唆犯罪的; 8.
                                                侮辱或者诽谤他人,侵害他人合法权益的; 9.  含有法律、行政法规禁止的其他内容的。
                                         </p>
                                         <p>
                                            四、有关个人资料
用户同意: 1. 提供及时、详尽及准确的个人资料。 2. 同意接收来自本网站的信息。
                                                3. 不断更新注册资料,符合及时、详尽准确的要求。所有原始键入的资料将引用为注册资料。 4.
                                                本网站不公开用户的姓名、地址、电子邮箱和笔名。除以下情况外: a) 用户授权本站透露这些信息。  b)
                                                相应的法律及程序要求本站提供用户的个人资料。
                                         </p>
                                         <p>
                                            五、服务条款的修改
本网站有权在必要时修改服务条款,一旦条款及服务内容产生变动,本网站将会在重要页面上提示修改内容。如果不同意所改动的内容,用户可以主动取消获得的本网站信息服务。如果用户继续享用本网站信息服务,则视为接受服务条款的变动。
                                         </p>
                                         <p>
                                            六、用户隐私制度
尊重用户个人隐私是本网站的一项基本政策。所以,本网站一定不会在未经合法用户授权时公开、编辑或透露其注册资料及保存在本网站中的非公开内容,除非有法律许可要求或本网站在诚信的基础上认为透露这些信息在以下四种情况是必要的:
                                                1. 遵守有关法律规定,遵从本网站合法服务程序。 2. 保持维护本网站的商标所有权。 3.
                                                在紧急情况下竭力维护用户个人和社会大众的隐私安全。 4. 符合其他相关的要求。
                                         </p>
                                         <p>
                                            七、用户的帐号、密码和安全性
用户一旦注册成功,将获得一个密码和用户名。用户需谨慎合理的保存、使用用户名和密码。如果你不保管好自己的帐号和密码安全,将负全部责任。另外,每个用户都要对其帐户中的所有活动和事件负全责。你可随时根据指示改变你的密码。用户若发现任何非法使用用户帐号或存在安全漏洞的情况,请立即通告本网站。
                                                八、 拒绝提供担保
                                                用户明确同意信息服务的使用由用户个人承担风险。本网站不担保服务不会受中断,对服务的及时性,安全性,出错发生都不作担保,但会在能力范围内,避免出错。
                                         </p>
                                         <p>
                                            九、有限责任
如因不可抗力或其它本站无法控制的原因使本站销售系统崩溃或无法正常使用导致网上交易无法完成或丢失有关的信息、记录等本站会尽可能合理地协助处理善后事宜,并努力使客户免受经济损失,同时会尽量避免这种损害的发生。
                                         </p>
                                         <p>
                                            十、用户信息的储存和限制
本站有判定用户的行为是否符合国家法律法规规定及本站服务条款权利,如果用户违背本网站服务条款的规定,本网站有权中断对其提供服务的权利。
                                         </p>
                                         <p>
                                            十一、用户管理
用户单独承担发布内容的责任。用户对服务的使用是根据所有适用于本站的国家法律、地方法律和国际法律标准的。用户必须遵循:
                                                1. 使用网络服务不作非法用途。 2. 不干扰或混乱网络服务。 3.
                                                遵守所有使用网络服务的网络协议、规定、程序和惯例。
                                                用户须承诺不传输任何非法的、骚扰性的、中伤他人的、辱骂性的、恐性的、伤害性的、庸俗的,淫秽等信息资料。另外,用户也不能传输何教唆他人构成犯罪行为的资料;不能传输助长国内不利条件和涉及国家安全的资料;不能传输任何不符合当地法规、国家法律和国际法律的资料。未经许可而非法进入其它电脑系统是禁止的。
                                                若用户的行为不符合以上提到的服务条款,本站将作出独立判断立即取消用户服务帐号。用户需对自己在网上的行为承担法律责任。用户若在本站上散布和传播反动、色情或其它违反国家法律的信息,本站的系统记录有可能作为用户违反法律的证据。
                                         </p>
                                         <p>
                                            十二、通告
所有发给用户的通告都可通过重要页面的公告或电子邮件或常规的信件传送。服务条款的修改、服务变更、或其它重要事件的通告都会以此形式进行。
                                         </p>
                                         <p>
                                            十三、信息内容的所有权
本网站定义的信息内容包括:
                                                文字、软件、声音、相片、录象、图表;在广告中全部内容;本网站为用户提供的其它信息。所有这些内容受版权、商标、标签和其它财产所有权法律的保护。所以,用户只能在本网站和广告商授权下才能使用这些内容,而不能擅自复制、再造这些内容、或创造与内容有关的派生产品。本站所有的文章版权归原文作者和本站共同所有,任何人需要转载本站的文章,必须征得原文作者或本站授权。
                                         </p>
                                         <p>
                                            十四、法律
本协议的订立、执行和解释及争议的解决均应适用中华人民共和国的法律。用户和本网站一致同意服从本网站所在地有管辖权的法院管辖。如发生本网站服务条款与中华人民共和国法律相抵触时,则这些条款将完全按法律规定重新解释,而其它条款则依旧保持对用户的约束力。
                                         </p>
                                     </div></td>
                              </tr>
                          </tbody>
                      </table>
                      <div class="login">
                          <div class="ad">
                              <dl>
                                 <dt>注册即享受</dt>
                                 <dd>正品保障、正规发票</dd>
                                 <dd>货到付款、会员服务</dd>
                                 <dd>自由退换、售后上门</dd>
                              </dl>
                          </div>
                          <dl>
                              <dt>已经拥有账号了?</dt>
                              <dd>
                                 立即登录即可体验在线购物! <a href="login.jsp">立即登录</a>
                              </dd>
                          </dl>
                      </div>
                  </form>
               </div>
           </div>
       </div>
    </div>
    <div class="container footer">
       <div class="span24">
           <div class="footerAd">
               <img src="image/footer.jpg"
                  width="950" height="52"  alt="我们的优势" title="我们的优势">
           </div>
       </div>
       <div class="span24">
           <ul class="bottomNav">
               <li><a>关于我们</a> |</li>
               <li><a>联系我们</a> |</li>
               <li><a>招贤纳士</a> |</li>
               <li><a>法律声明</a> |</li>
               <li><a>友情链接</a> |</li>
               <li><a target="_blank">支付方式</a> |</li>
               <li><a target="_blank">配送方式</a> |</li>
               <li><a>服务声明</a> |</li>
               <li><a>广告声明</a></li>
           </ul>
       </div>
       <div class="span24">
           <div class="copyright">Copyright  © 2005-2013 Mango商城 版权所有</div>
       </div>
    </div>
    <div id="_my97DP"
       style="position: absolute; top:  -1970px; left: -1970px;">
       <iframe style="width: 190px; height:  191px;"
           src="./会员注册 - Powered By  Mango Team_files/My97DatePicker.htm"
           frameborder="0" border="0"  scrolling="no"></iframe>
    </div>
</body>
</html>

BaseServlet.java

自定义的Servlet基类

利用反射机制,调用子类方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.yc.damai.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 自定义的Servlet基类
*/
public abstract class BaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通过op参数决定调用的方法
        String op = request.getParameter("op");

        // 根据 op 来执行 子类 的 业务方法 , java 反射:动态执行java方法
        // 获取类对象
        Class<?> cls = this.getClass();
        try {
            // Method java 方法对象
            Method m = cls.getMethod(op, HttpServletRequest.class, HttpServletResponse.class);
            // 通过 java 的反射机制, 动态执行方法
            m.invoke(this, request, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

UserServlet.java

业务处理

servlet逻辑关系:本UserServlet 继承 BaseServlet(包含doGet和doPost方法)再继承 HttpServlet

%!(EXTRA markdown.ResourceType=, string=, string=)

%!(EXTRA markdown.ResourceType=, string=, string=)

%!(EXTRA markdown.ResourceType=, string=, string=)

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
package com.yc.damai.servlet;

import java.io.IOException;
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 org.apache.commons.beanutils.BeanUtils;

import com.google.gson.Gson;
import com.yc.damai.bean.Result;
import com.yc.damai.bean.User;
import com.yc.damai.biz.BizException;
import com.yc.damai.biz.UserBiz;
/*
* user.s?op=reg  注册
* user.s?op=login  登录
* user.s?op=query  查询
* user.s?op=remove  移除
*/
@WebServlet("/user.s")
public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    /**
     * 全局域可以放 逻辑判断类。
     * 请谨慎放置,否则可能造成线程不安全。
     */
    
    private UserBiz biz = new UserBiz();
    
     /**
     * 子类的业务方法必须是  public 访问域
     */
    // 查询
    public void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    // 登录
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    
    //注册
    public void reg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        //数据装载
        User user = new User();
        try {
            //需要导入 commons-beanutils 和 commons-logging JAR包
         //将超链接里的参数一股脑的放入user对象中,通过参数名和对象中的变量名匹对。
            BeanUtils.populate(user, request.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        Result result;
        try {

            biz.reg(user, request.getParameter("repassword"));

            result = Result.success("注册成功!");
        } catch (BizException e) {
            result = Result.success(e.getMessage());
            e.printStackTrace();
        }
        
        //需要导入 gson JAR包
      //将 result 转成 json 字符串
      Gson gson = new Gson();
        String json = gson.toJson(result);
        response.getWriter().print(json);
    }
}

User.java

专门用于存放用户信息的对象,封装。

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
package com.yc.damai.bean;
public class User {
    private Long uid;
    private String username;
    private String password;
    private String name;
    private String email;
    private String phone;
    private String sex;
    private Integer state;
    private String code;
    private String addr;
    
    public Long getUid() {
       return uid;
    }
    public void setUid(Long uid) {
       this.uid = uid;
    }
    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 String getName() {
       return name;
    }
    public void setName(String name) {
       this.name = name;
    }
    public String getEmail() {
       return email;
    }
    public void setEmail(String email) {
       this.email = email;
    }
    public String getPhone() {
       return phone;
    }
    public void setPhone(String phone) {
       this.phone = phone;
    }
    public String getSex() {
       return sex;
    }
    public void setSex(String sex) {
       this.sex = sex;
    }
    public Integer getState() {
       return state;
    }
    public void setState(Integer state) {
       this.state = state;
    }
    public String getCode() {
       return code;
    }
    public void setCode(String code) {
       this.code = code;
    }
    public String getAddr() {
       return addr;
    }
    public void setAddr(String addr) {
       this.addr = addr;
    }
    
}

Result.java

专门用于存放信息的对象,封装。

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
package com.yc.damai.bean;
/*
* 用于封装ajax 请求返回数据类
*/
public class Result {
    //返回消息
    private String msg;
    //返回结果码 0失败 1成功
    private int code;
    //返回数据
    private Object data;
    
    /*
     * 默认成功的结果对象
     */
    public static Result success(String msg)  {
       Result result = new Result();
       result.code = 1;
       result.msg = msg;
       return result;
    }
    
    /*
     * 默认失败的结果对象
     */
    public static Result failure(String msg)  {
       //由于使用的是静态方法,因此可以在方法内new新对象,制作出不同的Result实例对象。
       Result result = new Result();
       result.code = 0;
       result.msg = msg;
       return result;
    }
    public String getMsg() {
       return msg;
    }
    public void setMsg(String msg) {
       this.msg = msg;
    }
    public int getCode() {
       return code;
    }
    public void setCode(int code) {
       this.code = code;
    }
    public Object getData() {
       return data;
    }
    public void setData(Object data) {
       this.data = data;
    }
}

UserBiz.java

注册新用户时,逻辑判断是否符合规则。

正常结束:调用UserDao.java,将用户信息写入数据库。

异常结束:当不符合规则,抛出异常,由UserServlet.java接收。

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
package com.yc.damai.biz;

import com.yc.damai.bean.User;
import com.yc.damai.dao.UserDao;

public class UserBiz {
    private UserDao dao = new UserDao();
    /*
     * 注册用户
     * 逻辑判断
     */
    public void reg(User user,String repassword) throws BizException {
        if(user.getUsername()==null || user.getUsername().trim().isEmpty()) {
            throw new BizException("请输入用户名!");
        }
        if(user.getPassword()==null || user.getPassword().trim().isEmpty()) {
            throw new BizException("请输入用户名!");
        }
        if(user.getPassword().equals("repassword")) {
            throw new BizException("两次输入密码不一致!");
        }
        
        //邮箱、电话、密码程度...

        dao.insert(user);
    }
}

UserDao.java

将用户信息写入数据库。

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

import com.yc.damai.bean.User;
import com.yc.damai.util.DBHelper;

public class UserDao {

    public void insert(User user) {
        String sql = "insert into user "+
                     "values(null,?,?,?,?,?,?,null,null,null)";
        DBHelper.update(sql,user.getUsername(),
                    user.getPassword(),
                    user.getName(),
                    user.getEmail(),
                    user.getPhone(),
                    user.getSex());
    }
}

BizException.java

异常类

实际上是重写了Exception(父类)的所有构造方法。

d2a5f83f66687564d98c6f53c3796a17.png

79c352af2d63d9771bc8a9a14479d236.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.yc.damai.biz;
public class BizException extends Exception{
    public BizException() {
       super();
       // TODO 自动生成的构造函数存根
    }
    public BizException(String message,  Throwable cause, boolean enableSuppression,  boolean writableStackTrace) {
       super(message, cause,  enableSuppression, writableStackTrace);
       // TODO 自动生成的构造函数存根
    }
    public BizException(String message,  Throwable cause) {
       super(message, cause);
       // TODO 自动生成的构造函数存根
    }
    public BizException(String message) {
       super(message);
       // TODO 自动生成的构造函数存根
    }
    public BizException(Throwable cause) {
       super(cause);
       // TODO 自动生成的构造函数存根
    }
}
CATALOG