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

Source: Internet
Author: User

Recently seen Lao Luo Video, made a simple user registration system. The user enters the user name, the real name, and the password through the Web page (JSP), and the servlet receives the information through JDBC and saves it to MySQL. Although is a simple can no longer simple things, but small, perfectly formed, in this do an induction and collation. The following first source:

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" >It runs the following results:


Second, click on the "click to register" 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" >
The results are as follows:

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 a perfect carrier for understanding the MVC architecture idea, with four packages, one file per package. Methodical in the division of functions.

1, Com.product.jdbc.dbutil This package is 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 ("registered successfully"), Response.sendredirect (path + "/ Index.jsp ");} ELSE{OUT.PRINTLN ("registration 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 Here the service 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 ();} /* Complete user write to registered DAO * @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, here are the key points for development:

1, about the problem of Chinese garbled, according to the old Luo's video at the beginning of my also garbled, after the study needs 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 code for response and request at the same time in the servlet, as follows:

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

2, about JSP to JSP page jump is very simple:

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

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 defining the Dosubmit () function:

<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>

Obtain a form and then obtain the corresponding 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 method browser address changes, parameters can be re-URL address or session, can not use Request.setattribute to pass parameters. Another way to use forward, 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 folder under the Webroot folder.

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

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

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.