基于Servlet、JSP、JDBC、MySQL的一个简单的用户注册模块(附完整源码)

来源:互联网 发布:买哪个星空软件 编辑:程序博客网 时间:2024/03/29 03:24

最近看老罗视频,做了一个简单的用户注册系统。用户通过网页(JSP)输入用户名、真名和密码,Servlet接收后通过JDBC将信息保存到MySQL中。虽然是个简单的不能再简单的东西,但麻雀虽小,五脏俱全,在此做一归纳和整理。下面先上源码:

一、index.jsp

[plain] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <title>后台管理系统</title>  
  11.     <meta http-equiv="pragma" content="no-cache">  
  12.     <meta http-equiv="cache-control" content="no-cache">  
  13.     <meta http-equiv="expires" content="0">      
  14.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  15.     <meta http-equiv="description" content="This is my page">  
  16.     <!--  
  17.     <link rel="stylesheet" type="text/css" href="styles.css">  
  18.     -->  
  19.   </head>  
  20.     
  21.   <body>  
  22.     <h1 align=center>欢迎您的注册  
  23.     </h1>  
  24.     <br>  
  25.     <font size="6"><a href="<%=path%>/pass.jsp"><font color="#0000ff">点击注册 </font>  
  26.     </a></font>  
  27.   </body>  
  28. </html>  
它的运行结果如下:


二、点击上面的“点击注册”就跳转到了pass.jsp:

[plain] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>  
  2. <%  
  3.     String path = request.getContextPath();  
  4. %>  
  5.   
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8. <head>  
  9. <title>后台管理系统</title>  
  10. <meta http-equiv=Content-Type content="text/html; charset=utf-8">  
  11. <meta http-equiv="pragma" content="no-cache">  
  12. <meta http-equiv="cache-control" content="no-cache">  
  13. <meta http-equiv="expires" content="0">  
  14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  15. <meta http-equiv="description" content="This is my page">  
  16. <style type="text/css">  
  17. .neon {  
  18.     FILTER: glow(color = #002E60, strength  = 3)  
  19. }  
  20.   
  21. DIV {  
  22.     WIDTH: 70px  
  23. }  
  24.   
  25. BODY {  
  26.     MARGIN: 0px  
  27. }  
  28.   
  29. BODY {  
  30.     MARGIN-TOP: 0px;  
  31.     SCROLLBAR-FACE-COLOR: #005fc5;  
  32.     FONT-SIZE: 12px;  
  33.     BACKGROUND: #ffffff;  
  34.     SCROLLBAR-HIGHLIGHT-COLOR: #799ae1;  
  35.     SCROLLBAR-SHADOW-COLOR: #799ae1;  
  36.     SCROLLBAR-3DLIGHT-COLOR: #005fc5;  
  37.     SCROLLBAR-ARROW-COLOR: #ffffff;  
  38.     SCROLLBAR-TRACK-COLOR: #aabfec;  
  39.     SCROLLBAR-DARKSHADOW-COLOR: #799ae1  
  40. }  
  41. </STYLE>  
  42. <LINK href="<%=path%>/images/duan_1.css" type=text/css rel=stylesheet>  
  43. <META content="MSHTML 6.00.2800.1106" name=GENERATOR>  
  44. <style type="text/css">  
  45. .style6 {  
  46.     COLOR: #0000ff  
  47. }  
  48.   
  49. .STYLE7 {  
  50.     COLOR: #003366;  
  51.     font-size: 12px;  
  52. }  
  53. </style>  
  54. <script type="text/javascript">  
  55.     function dosubmit() {  
  56.         var th = document.form1;  
  57.         if (th.username.value == "") {  
  58.             alert("用户名不能为空");  
  59.             th.username.focus();  
  60.             return;  
  61.         }  
  62.   
  63.         if (th.realname.value == "") {  
  64.             alert("姓名 不能为空");  
  65.             th.realname.focus();  
  66.             return;  
  67.         }  
  68.   
  69.         if (th.pswd.value == "") {  
  70.             alert("密码不能为空");  
  71.             th.pswd.focus();  
  72.             return;  
  73.         }  
  74.         th.action="<%=path%>/servlet/RegisterAction"  
  75.         th.submit();  
  76.   
  77.     }  
  78. </script>  
  79. </head>  
  80.   
  81. <body bgColor=#ffffff  
  82.     onload="MM_preloadImages('<%=path%>/images/ok_2.jpg', '<%=path%>/images/fh_2.jpg')">  
  83.     <form action="" name="form1" method="post">  
  84.         <table height=470 cellSpacing=0 cellPadding=0 width=580 aligen=center  
  85.             border=0>  
  86.             <tbody>  
  87.                 <tr>  
  88.                     <td colSpan=3 height=9 />  
  89.                 </tr>  
  90.                 <tr>  
  91.                     <td vAlign=top width=8 background="<%=path%>/images/dhpddw.gif"  
  92.                         rowSpan=2>  
  93.                         <!-- DWLayoutEmptyCell -->  </td>  
  94.                     <td background="<%=path%>/images/h-1.gif" height=9></td>  
  95.                     <td width=9 height=9><IMG height=9  
  96.                         src="<%=path%>/images/jiao.gif" width=9>  
  97.                     </td>  
  98.                 </tr>  
  99.                 <tr>  
  100.                     <td vAlign=top align=right width=743 height=452>  
  101.                         <table cellSpacing=0 cellPadding=0 width=556 border=0>  
  102.                             <!-- DWLayoutTable -->  
  103.                             <tbody>  
  104.                                 <tr>  
  105.                                     <td vAligh=bottom width=548 height=27><IMG height=10  
  106.                                         src="<%=path%>/images/jt2.gif" width=10> <span  
  107.                                         class="1bt">用户注册</span>  
  108.                                     </td>  
  109.                                     <td width=8 rowSpan=3> </td>  
  110.                                 </tr>  
  111.                                 <tr>  
  112.                                     <td bgColor="#ffffff" height=22></td>  
  113.                                 </tr>  
  114.                                 <tr>  
  115.                                     <td class=unnamed1 vAligh=top height=9>  
  116.                                         <table width="99%" border=0 cellPadding=4 cellSpacing=1  
  117.                                             bgColor="#0867b3">  
  118.                                             <tbody>  
  119.                                                 <TR bgColor=#ffffff height=20>  
  120.                                                     <TD width=14% noWrap class="STYLE7">用户名</TD>  
  121.                                                     <TD width=24% valign="top" noWrap><INPUT class=text2  
  122.                                                         maxLength=20 size=18 name="username" minLength="1">  
  123.                                                     </TD>  
  124.                                                     <TD width=62% noWrap><span class="STYLE7">必须填写!</span>  
  125.                                                     </TD>  
  126.                                                 </TR>  
  127.                                                 <TR bgColor=#ffffff height=20>  
  128.                                                     <TD height="4" noWrap><span class="STYLE7">姓  名</span>  
  129.                                                     </TD>  
  130.                                                     <TD height="4" valign="top" noWrap><INPUT class=text2  
  131.                                                         maxLength=20 size=18 name="realname" minLength="1">  
  132.                                                     </TD>  
  133.                                                     <TD height="4" noWrap><span class="STYLE7">必须填写!</span>  
  134.                                                     </TD>  
  135.                                                 </TR>  
  136.                                                 <TR bgColor=#ffffff height=20>  
  137.                                                     <TD height="2" noWrap><span class="STYLE7">密码 </span>  
  138.                                                     </TD>  
  139.                                                     <TD height="2" valign="top" noWrap><INPUT  
  140.                                                         type="password" class=text2 maxLength=20 size=18  
  141.                                                         name="pswd" minLength="1">  
  142.                                                     </TD>  
  143.                                                     <TD height="2" noWrap><span class="STYLE7">必填项</span>  
  144.                                                     </TD>  
  145.                                                 </TR>  
  146.                                             </tbody>  
  147.                                         </table> <br>  
  148.                                     </td>  
  149.                                 </tr>  
  150.                                 <TR>  
  151.                                     <TD height=20 align="center"><a  
  152.                                         href="javascript:dosubmit();"><img  
  153.                                             src="<%=path%>/images/ok_1.jpg" name="Image8" width="60"  
  154.                                             height="22" border="0"> </a>  <a  
  155.                                         href="<%=path%>/index.jsp"><img  
  156.                                             src="<%=path%>/images/fh_1.jpg" name="Image9" width="60"  
  157.                                             height="22" border="0"> </a>  
  158.                                     </TD>  
  159.                                     <TD></TD>  
  160.                                 </TR>  
  161.                             </tbody>  
  162.                         </table>  
  163.                     </td>  
  164.                     <TD width=9 background="<%=path%>/images/s-1.gif"></TD>  
  165.                 </tr>  
  166.             </tbody>  
  167.         </table>  
  168.     </form>  
  169. </body>  
  170. </html>  
  171. </span>  
运行效果如下:

三、除上面两个jsp代码外,剩下的就是java代码了。先来看java代码的结构:


不得不说JavaWeb是一个绝好的理解MVC架构思想的载体,上述有四个包,每个包下面一个文件。在功能的划分上有条不紊。

1、com.product.jdbc.dbutil 这个包里是基于jdbc驱动的一个工具类JdbcUtils.java,代码已经贴出来了,参见前文

2、com.product.register.action所谓的action扮演了MVC里的C的角色,即Control层,里面放的是各种Servlet。接收来自V(View)---客户端页面jsp回传的数据,然后调M层,把数据存进去。RegisterAction.java的代码:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;font-size:18px;">package com.product.register.action;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import org.hibernate.validator.util.GetConstructor;  
  14.   
  15. import com.product.register.dao.RegisterDao;  
  16. import com.product.register.service.RegisterService;  
  17.   
  18. public class RegisterAction extends HttpServlet {  
  19.   
  20.     /** 
  21.      *  
  22.      */  
  23.     private static final long serialVersionUID = 1L;  
  24.     private RegisterService service;  
  25.   
  26.     /** 
  27.      * Constructor of the object. 
  28.      */  
  29.     public RegisterAction() {  
  30.         super();  
  31.     }  
  32.   
  33.     /** 
  34.      * Destruction of the servlet. <br> 
  35.      */  
  36.     public void destroy() {  
  37.         super.destroy(); // Just puts "destroy" string in log  
  38.         // Put your code here  
  39.     }  
  40.   
  41.     /** 
  42.      * The doGet method of the servlet. <br> 
  43.      * 
  44.      * This method is called when a form has its tag value method equals to get. 
  45.      *  
  46.      * @param request the request send by the client to the server 
  47.      * @param response the response send by the server to the client 
  48.      * @throws ServletException if an error occurred 
  49.      * @throws IOException if an error occurred 
  50.      */  
  51.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  52.             throws ServletException, IOException {  
  53.   
  54.         this.doPost(request, response);  
  55.     }  
  56.   
  57.     /** 
  58.      * The doPost method of the servlet. <br> 
  59.      * 
  60.      * This method is called when a form has its tag value method equals to post. 
  61.      *  
  62.      * @param request the request send by the client to the server 
  63.      * @param response the response send by the server to the client 
  64.      * @throws ServletException if an error occurred 
  65.      * @throws IOException if an error occurred 
  66.      */  
  67.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  68.             throws ServletException, IOException {  
  69. String path = request.getContextPath();  
  70.     request.setCharacterEncoding("UTF-8");  
  71.         response.setContentType("text/html; charset=utf-8");  
  72.         PrintWriter out = response.getWriter();  
  73.         String username = request.getParameter("username");  
  74.         String realname = request.getParameter("realname");  
  75.         String pswd = request.getParameter("pswd");  
  76.         System.out.println("username = " + username + "  realname = " + realname  
  77.                 +" pswd = " + pswd);  
  78.         List<Object> params = new ArrayList<Object>();  
  79.         params.add(username);  
  80.         params.add(pswd);  
  81.         params.add(realname);  
  82.         boolean flag = service.registerUser(params);  
  83.         if(flag){  
  84.             out.println("注册成功");  
  85.             response.sendRedirect(path + "/index.jsp");  
  86.         }else{  
  87.             out.println("注册失败");  
  88.         }  
  89.         out.flush();  
  90.         out.close();  
  91.     }  
  92.   
  93.     /** 
  94.      * Initialization of the servlet. <br> 
  95.      * 
  96.      * @throws ServletException if an error occurs 
  97.      */  
  98.     public void init() throws ServletException {  
  99.         // Put your code here  
  100.         service = new RegisterDao();   
  101.     }  
  102.   
  103. }  
  104. </span>  

3.com.product.register.service 这里的service其实是一个接口,RegisterService.java代码:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;font-size:18px;">package com.product.register.service;  
  2.   
  3. import java.util.List;  
  4.   
  5.   
  6. public interface RegisterService {  
  7.     public boolean registerUser(List<Object> params);  
  8. }</span>  

4.既然有接口就一定有接口的实现者,实现者就是com.product.register.dao下的RegisterDao.java, 负责操纵数据库,将信息存到表里。

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;font-size:18px;">package com.product.register.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.product.jdbc.dbutil.JdbcUtils;  
  6. import com.product.register.service.RegisterService;  
  7.   
  8. public class RegisterDao implements RegisterService {  
  9.     private JdbcUtils jdbcUtils = null;  
  10.     public RegisterDao() {  
  11.         // TODO Auto-generated constructor stub  
  12.         jdbcUtils = new JdbcUtils();  
  13.     }  
  14.   
  15.     /* 完成用户对注册的Dao的编写 
  16.      * @see com.product.register.service.RegisterService#registerUser(java.util.List) 
  17.      */  
  18.     @Override  
  19.     public boolean registerUser(List<Object> params) {  
  20.         // TODO Auto-generated method stub  
  21.         boolean flag = false;  
  22.         jdbcUtils.getConnection();  
  23.         String sql = "insert into userinfo(username, pswd, realname) values (?, ?, ?)";  
  24.         try{  
  25.             flag = jdbcUtils.updateByPreparedStatement(sql, params);  
  26.         }catch(Exception e){  
  27.             e.printStackTrace();  
  28.         }  
  29.         finally{  
  30.             jdbcUtils.releaseConn();  
  31.         }  
  32.           
  33.         return flag;  
  34.     }  
  35.   
  36. }  
  37. </span>  

下图是输入一个用户的信息:



用Navicat打开数据库可以看到:



代码就完毕了,下面是开发要点:

1、关于中文乱码的问题,按老罗的视频一开始我的也乱码,经研究需要三个地方同时设置utf-8编码,第一是数据库里表的编码,第二是jsp的编码:pageEncoding="utf-8" 第三是在Servlet里同时设置response和request的编码,代码如下:

request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8"); 记住是缺一不可哦!!!

2、关于JSP往JSP页面的跳转很简单:

<a href="<%=path%>/pass.jsp">点击注册</a> 超链接里直接放要跳转jsp的相对路径即可。

3、JSP往Servlet跳转:

<a  href="javascript:dosubmit();">

<img src="<%=path%>/images/ok_1.jpg" name="Image8" width="60" height="22" border="0"> </a> 

也是用的href超链接,在地址里写"javascript:dosubmit();". 这就需要定义dosubmit()函数:

[javascript] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:Comic Sans MS;font-size:18px;"><script type="text/javascript">  
  2.     function dosubmit() {  
  3.         var th = document.form1;  
  4.         if (th.username.value == "") {  
  5.             alert("用户名不能为空");  
  6.             th.username.focus();  
  7.             return;  
  8.         }  
  9.   
  10.         if (th.realname.value == "") {  
  11.             alert("姓名 不能为空");  
  12.             th.realname.focus();  
  13.             return;  
  14.         }  
  15.   
  16.         if (th.pswd.value == "") {  
  17.             alert("密码不能为空");  
  18.             th.pswd.focus();  
  19.             return;  
  20.         }  
  21.         th.action="<%=path%>/servlet/RegisterAction"  
  22.         th.submit();  
  23.   
  24.     }  
  25. </script></span>  

获得一个表单,然后根据input时的名字获取对应value,

<INPUT class=text2maxLength=20 size=18 name="username" minLength="1"> 

4、上面可以看到jsp往servlet跳转过程中先经过javascript,接下来说白了是javascript往servlet跳转:

th.action="<%=path%>/servlet/RegisterAction"
th.submit();

5、Servlet往jsp跳转:

response.sendRedirect(path + "/index.jsp");这种方法浏览器地址发生变化,传参数可以再URL地址里或用session,不能使用request.setAttribute来传参数。另一种使用forward来传,详细参见这里: 链接1   链接2

6、纵观整个架构,RegisterAction是控制中枢,数据经jsp----javascript传到RegisterAction。在RegisterAction里创建了接口Service的实例RegisterDao,用Dao来存数据。

关于javaEE的各层分工,详见这里

7.因为要访问数据库,记得将mysql-connector-java-5.1.26-bin.jar拷贝到WebRoot文件夹下的WEB-INF/lib文件夹下。

另外在web.xml里要配对,jsp里用到了css。其他的细节看源码吧。

下载链接:http://download.csdn.net/detail/yanzi1225627/7442677

1 0