A simple user registration module based on servlet, JSP, JDBC, and MySQL (complete source code included)

Source: Internet
Author: User

See Lao Luo recently video, did a simple user register system. The user enters the user name, the real name, and the Password,servlet through the Web page (JSP) to save the information to MySQL via JDBC. Although it is a simple thing can not be simple, but small, perfectly formed, here do an induction and collation. The following first source code:

First, 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" >The results of its execution are as follows:


Second, click on the "click Register" above to jump to the 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" >
performance effects such as the following:

Third, in addition to the above two JSP code, the rest is Java code. Let's look at the structure of the Java code:


I have to say that Javaweb is an excellent carrier for understanding the idea of MVC architecture, which has four packages, one file per package. Methodical in the division of functions.

1, Com.product.jdbc.dbutil This package is based on a JDBC-driven tool class Jdbcutils.java, the code has been posted, see the previous article

2, com.product.register.action so-called action plays the role of C in MVC, that is, the control layer, which puts a variety of servlet. Receives the data from the V (View)---Client page JSP callback, then the M layer, the data is stored in. Registeraction.java's Code:

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 Servi ce;/** * 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 D Oget method of the servlet. <br> * This method was called when a form have 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 IO Exception If an error occurred */public void doget (HttpServletRequest request, httpservletresponse response) throws Servle Texception, IOException {this.dopost (request, response);} /** * The DoPost method of the servlet. <br> * This method was called when a form have 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 (HTT Pservletrequest 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> ();p arams.add (username);p Arams.add (pswd);p Arams.add ( Realname), Boolean flag = Service.registeruser (params), if (flag) {OUT.PRINTLN ("register Success"), Response.sendredirect (path + "/ Index.jsp ");} ELSE{OUT.PRINTLN ("Register Failed");} 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 The service here is actually an interface, Registerservice.java code:

Package Com.product.register.service;import Java.util.list;public Interface Registerservice {public boolean RegisterUser (list<object> params);}

4. Since there must be an interface to the implementation of the interface, the implementation is Com.product.register.dao under the Registerdao.java, responsible for manipulating the database, the information stored in the table.

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 ();} /* Completed the user's writing of the DAO of the Register * @see Com.product.register.service.registerservice#registeruser (java.util.List) */@ Overridepublic boolean RegisterUser (list<object> params) {//TODO auto-generated method Stubboolean flag = False;jd Bcutils.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;}}

is to enter information for a user:



Open the database with Navicat to see:



The code is complete, the following are the development points:

1, about the problem of Chinese garbled, according to the old Luo's video began my also garbled, after the study need three places at the same time set Utf-8 code, the first is the database table encoding, the second is the code of the JSP: pageencoding= "Utf-8" The third is to set the encoding for response and request at the same time in the servlet code, such as the following:

Request.setcharacterencoding ("Utf-8");
Response.setcontenttype ("text/html; Charset=utf-8 "); Remember is indispensable Oh!!!

2, about JSP to JSP page jump very easy:

<a href= "<%=path%>/pass.jsp" > click on the Register </a> hyperlink to jump directly to the relative path of the JSP can be.

3, JSP to the servlet jump:

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

/images/ok_1.jpg" name= "Image8" width= "height=" "border=" 0 "> </a>

Also use the href hyperlink, which is written in the address "javascript:dosubmit ();". This requires the Dosubmit () function to be defined:

<script type= "Text/javascript" >function dosubmit () {var th = document.form1;if (Th.username.value = = "") {alert (" User name cannot be empty "); Th.username.focus (); return;} if (Th.realname.value = = "") {alert ("Name cannot be empty"); Th.realname.focus (); return;} if (Th.pswd.value = = "") {alert ("Password cannot be empty"); Th.pswd.focus (); return;} th.action= "<%=path%>/servlet/registeraction" Th.submit ();} </script>

Get a form and then get the value based on the name of input ,

<input class=text2maxlength=20 size=18 name= "username" minlength= "1" >

4, the above can see the JSP to the servlet jump process first through JavaScript, and then plainly is JavaScript to the servlet jump:

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

5, servlet to JSP Jump:

Response.sendredirect (path + "/index.jsp"); This way the browser address changes, the number of references can be in the URL address or session, you can not use Request.setattribute to pass the number of references. There is also a use of forward to pass, specifically see here: Link 1 Link 2

6, throughout the architecture, Registeraction is the control center, the data by JSP----JavaScript to registeraction. In Registeraction, an instance of the interface service is created Registerdao, which uses DAO to store data.

For each layer of Java EE Division, see here

7. To access the database, remember to copy the Mysql-connector-java-5.1.26-bin.jar to the Web-inf/lib directory under the Webroot directory.

In addition, in the Web. Xml to match, JSP used CSS. Other details look at the source code bar.

Download Link: http://download.csdn.net/detail/yanzi1225627/7442677

A simple user registration module based on servlet, JSP, JDBC, and MySQL (complete source code included)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.