最近看老罗视频,做了一个简单的用户注册系统。用户通过网页(JSP)输入用户名、真名和密码,Servlet接收后通过JDBC将信息保存到MySQL中。虽然是个简单的不能再简单的东西,但麻雀虽小,五脏俱全,在此做一归纳和整理。下面先上源码:
一、index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1 align=center>欢迎您的注册 </h1> <br> <font size="6"><a href="<%=path%>/pass.jsp"><font color="#0000ff">点击注册 </font> </a></font> </body> </html>
它的运行结果如下:
二、点击上面的“点击注册”就跳转到了pass.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %> <% String path = request.getContextPath(); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>后台管理系统</title> <meta http-equiv=Content-Type content="text/html; charset=utf-8"> <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"> <style type="text/css"> .neon { FILTER: glow(color = #002E60, strength = 3) } DIV { WIDTH: 70px } BODY { MARGIN: 0px } BODY { MARGIN-TOP: 0px; SCROLLBAR-FACE-COLOR: #005fc5; FONT-SIZE: 12px; BACKGROUND: #ffffff; SCROLLBAR-HIGHLIGHT-COLOR: #799ae1; SCROLLBAR-SHADOW-COLOR: #799ae1; SCROLLBAR-3DLIGHT-COLOR: #005fc5; SCROLLBAR-ARROW-COLOR: #ffffff; SCROLLBAR-TRACK-COLOR: #aabfec; SCROLLBAR-DARKSHADOW-COLOR: #799ae1 } </STYLE> <LINK href="<%=path%>/images/duan_1.css" type=text/css rel=stylesheet> <META content="MSHTML 6.00.2800.1106" name=GENERATOR> <style type="text/css"> .style6 { COLOR: #0000ff } .STYLE7 { COLOR: #003366; font-size: 12px; } </style> <script type="text/javascript"> function dosubmit() { var th = document.form1; if (th.username.value == "") { alert("用户名不能为空"); th.username.focus(); return; } if (th.realname.value == "") { alert("姓名 不能为空"); th.realname.focus(); return; } if (th.pswd.value == "") { alert("密码不能为空"); th.pswd.focus(); return; } th.action="<%=path%>/servlet/RegisterAction" th.submit(); } </script> </head> <body bgColor=#ffffff onload="MM_preloadImages(‘<%=path%>/images/ok_2.jpg‘, ‘<%=path%>/images/fh_2.jpg‘)"> <form action="" name="form1" method="post"> <table height=470 cellSpacing=0 cellPadding=0 width=580 aligen=center border=0> <tbody> <tr> <td colSpan=3 height=9 /> </tr> <tr> <td vAlign=top width=8 background="<%=path%>/images/dhpddw.gif" rowSpan=2> <!-- DWLayoutEmptyCell --> </td> <td background="<%=path%>/images/h-1.gif" height=9></td> <td width=9 height=9><IMG height=9 src="<%=path%>/images/jiao.gif" width=9> </td> </tr> <tr> <td vAlign=top align=right width=743 height=452> <table cellSpacing=0 cellPadding=0 width=556 border=0> <!-- DWLayoutTable --> <tbody> <tr> <td vAligh=bottom width=548 height=27><IMG height=10 src="<%=path%>/images/jt2.gif" width=10> <span class="1bt">用户注册</span> </td> <td width=8 rowSpan=3> </td> </tr> <tr> <td bgColor="#ffffff" height=22></td> </tr> <tr> <td class=unnamed1 vAligh=top height=9> <table width="99%" border=0 cellPadding=4 cellSpacing=1 bgColor="#0867b3"> <tbody> <TR bgColor=#ffffff height=20> <TD width=14% noWrap class="STYLE7">用户名</TD> <TD width=24% valign="top" noWrap><INPUT class=text2 maxLength=20 size=18 name="username" minLength="1"> </TD> <TD width=62% noWrap><span class="STYLE7">必须填写!</span> </TD> </TR> <TR bgColor=#ffffff height=20> <TD height="4" noWrap><span class="STYLE7">姓 名</span> </TD> <TD height="4" valign="top" noWrap><INPUT class=text2 maxLength=20 size=18 name="realname" minLength="1"> </TD> <TD height="4" noWrap><span class="STYLE7">必须填写!</span> </TD> </TR> <TR bgColor=#ffffff height=20> <TD height="2" noWrap><span class="STYLE7">密码 </span> </TD> <TD height="2" valign="top" noWrap><INPUT type="password" class=text2 maxLength=20 size=18 name="pswd" minLength="1"> </TD> <TD height="2" noWrap><span class="STYLE7">必填项</span> </TD> </TR> </tbody> </table> <br> </td> </tr> <TR> <TD height=20 align="center"><a href="javascript:dosubmit();"><img src="<%=path%>/images/ok_1.jpg" name="Image8" width="60" height="22" border="0"> </a> <a href="<%=path%>/index.jsp"><img src="<%=path%>/images/fh_1.jpg" name="Image9" width="60" height="22" border="0"> </a> </TD> <TD></TD> </TR> </tbody> </table> </td> <TD width=9 background="<%=path%>/images/s-1.gif"></TD> </tr> </tbody> </table> </form> </body> </html>
运行效果如下:
三、除上面两个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的代码:
package com.product.register.action; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.validator.util.GetConstructor; import com.product.register.dao.RegisterDao; import com.product.register.service.RegisterService; public class RegisterAction extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private RegisterService service; /** * Constructor of the object. */ public RegisterAction() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getContextPath(); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); String username = request.getParameter("username"); String realname = request.getParameter("realname"); String pswd = request.getParameter("pswd"); System.out.println("username = " + username + " realname = " + realname +" pswd = " + pswd); List<Object> params = new ArrayList<Object>(); params.add(username); params.add(pswd); params.add(realname); boolean flag = service.registerUser(params); if(flag){ out.println("注册成功"); response.sendRedirect(path + "/index.jsp"); }else{ out.println("注册失败"); } out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here service = new RegisterDao(); } }
3.com.product.register.service 这里的service其实是一个接口,RegisterService.java代码:
package com.product.register.service; import java.util.List; public interface RegisterService { public boolean registerUser(List<Object> params); }
4.既然有接口就一定有接口的实现者,实现者就是com.product.register.dao下的RegisterDao.java, 负责操纵数据库,将信息存到表里。
package com.product.register.dao; import java.util.List; import com.product.jdbc.dbutil.JdbcUtils; import com.product.register.service.RegisterService; public class RegisterDao implements RegisterService { private JdbcUtils jdbcUtils = null; public RegisterDao() { // TODO Auto-generated constructor stub jdbcUtils = new JdbcUtils(); } /* 完成用户对注册的Dao的编写 * @see com.product.register.service.RegisterService#registerUser(java.util.List) */ @Override public boolean registerUser(List<Object> params) { // TODO Auto-generated method stub boolean flag = false; jdbcUtils.getConnection(); String sql = "insert into userinfo(username, pswd, realname) values (?, ?, ?)"; try{ flag = jdbcUtils.updateByPreparedStatement(sql, params); }catch(Exception e){ e.printStackTrace(); } finally{ jdbcUtils.releaseConn(); } return flag; } }
下图是输入一个用户的信息:
用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()函数:
<script type="text/javascript"> function dosubmit() { var th = document.form1; if (th.username.value == "") { alert("用户名不能为空"); th.username.focus(); return; } if (th.realname.value == "") { alert("姓名 不能为空"); th.realname.focus(); return; } if (th.pswd.value == "") { alert("密码不能为空"); th.pswd.focus(); return; } th.action="<%=path%>/servlet/RegisterAction" th.submit(); } </script>
获得一个表单,然后根据input时的名字获取对应value,
<INPUT class=text2 maxLength=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
基于Servlet、JSP、JDBC、MySQL的一个简单的用户注册模块(附完整源码)