基於Servlet、JSP、JDBC、MySQL的一個簡單的使用者注冊模組(附完整原始碼)

來源:互聯網
上載者:User

標籤:

近期看老羅視頻,做了一個簡單的使用者注冊系統。使用者通過網頁(JSP)輸入使用者名稱、真名和password,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("password不可為空");th.pswd.focus();return;}th.action="<%=path%>/servlet/RegisterAction"th.submit();}</script></head><body bgColor=#ffffffonload="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=centerborder=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=9src="<%=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=10src="<%=path%>/images/jt2.gif" width=10> <spanclass="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=1bgColor="#0867b3"><tbody><TR bgColor=#ffffff height=20><TD width=14% noWrap class="STYLE7">使用者名稱</TD><TD width=24% valign="top" noWrap><INPUT class=text2maxLength=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=text2maxLength=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">password </span></TD><TD height="2" valign="top" noWrap><INPUTtype="password" class=text2 maxLength=20 size=18name="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"><ahref="javascript:dosubmit();"><imgsrc="<%=path%>/images/ok_1.jpg" name="Image8" width="60"height="22" border="0"> </a>  <ahref="<%=path%>/index.jsp"><imgsrc="<%=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 hereservice = 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 stubjdbcUtils = new JdbcUtils();}/* 完畢使用者對注冊的Dao的編寫 * @see com.product.register.service.RegisterService#registerUser(java.util.List) */@Overridepublic boolean registerUser(List<Object> params) {// TODO Auto-generated method stubboolean 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頁面的跳轉非常easy:

<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("password不可為空");th.pswd.focus();return;}th.action="<%=path%>/servlet/RegisterAction"th.submit();}</script>

獲得一個表單,然後依據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

基於Servlet、JSP、JDBC、MySQL的一個簡單的使用者注冊模組(附完整原始碼)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.