"Servlet" Design user login, user registration, Change password system according to MVC idea

Source: Internet
Author: User

MVC is not a programming language like C, Java, or a technique like ajax,servlet, but an object-oriented programming idea. In recent years, MVC has been very hot, the praise of the batch of people, and then a large number of articles, but concise simple MVC example almost no. In the JSP field has been to the blower to blow the SSH how good, has been angry batch jsp,servlet how how bad. In fact, using Jsp+servlet can also use the MVC idea to complete a system. Below with a rotten can not be rotten example, you step into the Web programming must learn something, login, register, modify the password system, to illustrate this programming idea.


I. BASIC OBJECTIVES

On a form.jsp page there are three forms, namely login system, registration system, change password system, different situations give different information, such as:


Processing Servlets, which are those Java files, cannot be accessed directly by entering URLs.



Second, the basic idea

Site directory structure as shown, enter the form of the page form.jsp is called the View layer, click go! After the submission to the processing Java file login system Login.java, registration system Register.java, modify the password system Update.java inside not allowed to have any action database action, they can only send through form.jsp information, construct the corresponding SQL statement to DBDA O.java, in Dbdao.java the same operational database, these Java files are so-called controller layer, and then Dbdao.java is the so-called Javabean,java container under the DAO component, what business logic of the bullshit abstract things, that is, the model layer.


MVC programming idea, in the beginning to write the program is the most egg pain, its initial development speed than directly write the Java statement Operation database, What you think that is, of course, is written more than you have to manipulate the database of things abstracted out in a dbdao.java inside fast, but after you have developed a landing system, then the user registration system, change the password system will soon be able to complete, because all things are you abstracted good, changed very good change. This is the reason why some enterprises are strict with MVC to programming, first the first Division of labor is clear, the second one is changed to be good later, The most important thing is that they can use some technology to not let you see Dbdao.java, you just develop the view layer or controller can not fully grasp their underlying database is what. Even some programmers who specialize in model writing don't know what a bunch of data in a database is for. Only core executives know the process of the entire process. He is difficult to write your program, do not write, please roll rough.

MVC programming ideas have good or bad, here no longer discuss, the key is that you will. This is a threshold from the low-level program ape advanced to Intermediate program Ape. Here's how to implement these three systems at the same time using a servlet. Don't use complex ssh to get confused.

This thing is really not difficult, please do not frighten the large space, but I have discussed the JDBC technology "MySQL" Java database additions and deletions, Java System Class (click Open link) and servlet technology "servlet" The simplest servlet javaweb program (click the Open link) indicates the rendition.


Third, the production process


1, first or there is a test database, there is a user information table usertable, or such as the classic configuration, primary key, user name, password,


In the table there are already several user information, such as, supposedly, the password here should be stored by SHA-1 code, but in order to avoid too complex, here first in clear text storage:



2. Create a new Eclipse project, in the Lib folder, Put Javax.servlet-api-3.1.0.jar, to prevent some unknown Tomcat does not support servlet, this thing more than 3.0 can be, there is so-called MYSQLJDBC data source Mysql-connector-java-5.1.32.jar, this thing super Over 5.0. On the two jar package, a lot of online, put into the Lib folder is finished.



3, the configuration good servlet, writes the following code in the Web. xml file, indicates that the/login domain name jumps to the root directory the Login.java processing, the remainder is so analogy.

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_2_5.xsd "version=" 2.5 "><!--User Login--><servlet><servlet-name >login</servlet-name><servlet-class>login</servlet-class></servlet>< Servlet-mapping><servlet-name>login</servlet-name><url-pattern>/login</url-pattern> </servlet-mapping><!--User Registration--><servlet><servlet-name>register</servlet-name>< Servlet-class>register</servlet-class></servlet><servlet-mapping><servlet-name> register</servlet-name><url-pattern>/register</url-pattern></servlet-mapping><!-- User Modified password--><servlet><servlet-name>update</servlet-name><servlet-class>update</ Servlet-class></servlet><sErvlet-mapping><servlet-name>update</servlet-name><url-pattern>/update</url-pattern ></servlet-mapping></web-app>


4, after the MVC first write which has no relationship, I used to write V, because V is the simplest, on a presentation layer, not how to think, and then the user will produce what variables you can be clear after writing v. That's the form.jsp, which actually has three simple forms that can't be easily done. Put a JSP statement, check if there is a prompt message, if any, then output.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Supposedly, this JSP should also be omitted, so that the V layer is pure v layer, all the front-end code, should be directly using AJAX technology to complete the output of the error message, using DWR or Jqueryajax what JavaScript front-end technology, here in order not to complicate, Or use back to the simple JSP code to explain, and verify that two times the password is consistent, you should also use the "JavaScript" form to verify the instant, do not make the submission (click Open link) to do, but, also for a simple point, put on the C layer to deal with it. After understanding the MVC idea, everybody changes slowly.


5, re-write m, the operation of the database action abstract out, the connection database action in the constructor, the action to close the database in the destructor, and later in the C-layer even Con.close province, do not tell me that Java does not have destructors, protected void Finalize () And in the strict sense of the destructor, the actual result is no difference, only the concept of cumbersome differences, and then such as query, insert, modify data, generally do not write delete, because the custom set flag bit pseudo-deletion. When you close the data, let's see if the database is now connected.

This so-called persistent layer, generally written well, do not have to change. You just have to write C to call the M layer and return the result to the V layer.

Import java.sql.*;p Ublic class Dbdao {Private Connection con;//constructor, connection database public Dbdao () throws Exception {String Dburl = "Jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf8&useoldaliasmetadatabehavior= True "; String dbusername = "root"; String Dbpassword = "root"; Class.forName ("Com.mysql.jdbc.Driver"); This.con = Drivermanager.getconnection (Dburl, Dbusername, Dbpassword);} Execute Query Public ResultSet query (String sql, Object ... args) throws Exception {PreparedStatement PS = con.preparestatement (sq l); for (int i = 0; i < args.length; i++) {Ps.setobject (i + 1, args[i]);} return Ps.executequery ();} Execute Insert public boolean insert (String sql, Object ... args) throws Exception {PreparedStatement PS = con.preparestatement (sql ); for (int i = 0; i < args.length; i++) {Ps.setobject (i + 1, args[i]);} if (ps.executeupdate ()! = 1) {return false;} return true;} Execute Modify public boolean modify (String sql, Object ... args) throws Exception {PreparedStatement PS = con.preparestatement (sql ); for (int i = 0; i < args.length; i++) {Ps.setobject (i + 1, args[i]);} if (ps.executeupdate ()! = 1) {return false;} return true;} destructors, interrupting database connections protected void Finalize () throws Exception {if (!con.isclosed () | | con! = NULL) {Con.close ();}}}
There is no difference between this and the JDBC technology discussed earlier, "MySQL" Java database additions and deletions, the Java System Class (click to open the link), but note that there is a little bit of small stuff added here, through the "Java" JDK1.5 after the new type of generic parameter transfer method Object...args (click the Open link) to pass an SQL statement, with an object array, which has string strings and shaping int, here is to match SetObject method, For example, the SQL statement passed in is:

Update usertable set password=? where Username=?

The two object arguments are strings 11 and 22, by:

for (int i = 0; i < args.length; i++) {Ps.setobject (i + 1, args[i]);}
It will automatically put? Substitution is replaced in order with the object parameter you passed, forming a complete SQL statement for you to insert, modify, Delete method executeupdate () or Query method ExecuteQuery () using:
Update usertable set password= ' where Username= ' 22 '
If it is passed through, it will automatically remove the quotation marks to construct a complete statement. The so-called PreparedStatement object is that meaning!

Direct emphasis on insert, modify, delete method and Query method in JDBC is different, the former is executeupdate (), the latter is executequery (), that is because the former is not the return value, the latter has the reason for the return value Ah! Of course, packaged ASP and PHP are another matter.

Through the method above, now no matter what you pass a thing over, can be queried.


6, the last write C, this is the most difficult step, with the foundation of M and V to connect the two parts together. The servlet here does not use a service method to combine doget with Dopost, it is to separate them from the user directly into the URL to access this servlet, because the user directly enter the URL to access this servlet is called Doget method, The Dopost method is passed directly through the form, because I have already noted the form.


(1) The first is Login.java, the idea of landing nothing to say. This user name in the database corresponding to the password and the user entered the password match, is this success, whether this failure, not to find is the failure.

It can be seen clearly that there is nothing to manipulate the database.

Import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;p ublic class Login extends HttpServlet {//Prevents users from entering URLs directly to access this servletprotected void doget (httpservletrequest request,httpservletresponse response) Throws Servletexception, IOException {printstream out = new PrintStream (Response.getoutputstream ()); Response.setcontenttype ("Text/html;charset=utf-8"); Out.print ("Please open this page normally");} protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception {String errmsg = "";//Gets the user input something string username = Request.getparameter ("username"); String Password = request.getparameter ("password"); try {//constructs the statement of the operational database Dbdao db = new Dbdao (); ResultSet rs = db.query ("Select password from usertable where username=?", username);//Depending on the results of the query, return different results to the view layer if ( Rs.next ()) {if (rs.getstring ("password"). Equals (password)) {HttpSession session = Request.getsession (); Session.setattribute ("username", username); Request.getrequestdispatcher ("/welcome.jsp"). Forward (Request, reSponse);} else {errmsg = "bad password!" "; Request.setattribute (" ErrMsg ", errmsg); Request.getrequestdispatcher ("/form.jsp "). Forward (request,response);}} else {errmsg = "user name does not exist! "; Request.setattribute (" ErrMsg ", errmsg); Request.getrequestdispatcher ("/form.jsp "). Forward (request,response);}} catch (Exception e) {e.printstacktrace ();}}}
The error message here is only the request object, it is after the servlet returns the result to form.jsp after the message, and later on any page with Request.getattribute ("ErrMsg") will not get the return of the request for the prompt message. If the login is successful, the user name is stored in the Session object, this object is the default user does not close the browser will not disappear, has existed. Successful login, the user does not close the browser, on any page using Session.getattribute ("username") can get its user name, unless there is a statement to set the session's lifetime or immediate death.


(2) After the development of Register.java, you can be almost the same as the Login.java code, if you do not use MVC, you have to change the operation of the database, even if you write directly on the JSP page, like PHP and ASP development, not to change the words of the egg hurts, thought or that thought, first than the password entered by the user is consistent, and then query whether there is a user, not in the database to insert this message.

Import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;p ublic class Register extends HttpServlet {//Prevents users from entering URLs directly to access this servletprotected void doget (httpservletrequest request,httpservletresponse response) Throws Servletexception, IOException {printstream out = new PrintStream (Response.getoutputstream ()); Response.setcontenttype ("Text/html;charset=utf-8"); Out.print ("Please open this page normally");} protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception {String errmsg = ""; String username = request.getparameter ("username"); String Password = request.getparameter ("password"); String Passwordagain = Request.getparameter ("Passwordagain"); try {if (password.equals (Passwordagain)) {Dbdao db = new Dbdao (); ResultSet rs = db.query ("Select username from usertable where username=?", username), if (!rs.next ()) {Db.insert ("insert in To Usertable (Username,password) VALUES (?,?) ", username, password); errmsg =" Registered successfully! "; Request.setattribute (" ErrMsg ", errmsg); requEst.getrequestdispatcher ("/form.jsp"). Forward (request,response);} else {errmsg = "user name already exists! "; Request.setattribute (" ErrMsg ", errmsg); Request.getrequestdispatcher ("/form.jsp "). Forward (request,response);}} else {errmsg = "The password for two times entered is inconsistent"; Request.setattribute ("ErrMsg", errmsg); Request.getrequestdispatcher ("/form.jsp"). Forward (request,response);}} catch (Exception e) {e.printstacktrace ();}}}

(3) Change the password system, this has a large round of the foundation, it is easy, you just change to see the user two times the password is consistent, and then see whether the user can log on successfully, and finally modify the password corresponding to the user name.

Import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;p ublic class Update extends HttpServlet {//Prevents users from entering URLs directly to access this servletprotected void doget (httpservletrequest request,httpservletresponse response) Throws Servletexception, IOException {printstream out = new PrintStream (Response.getoutputstream ()); Response.setcontenttype ("Text/html;charset=utf-8"); Out.print ("Please open this page normally");} protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception {String errmsg = ""; String username = request.getparameter ("username"); String Password = request.getparameter ("password"); try {Dbdao db = new Dbdao (); ResultSet rs = db.query ("Select password from usertable where username=?", username), if (Rs.next ()) {if (Rs.getstring ("pas Sword "). Equals (password)) {String NewPassword = Request.getparameter (" NewPassword "); String Newpasswordagain = Request.getparameter ("Newpasswordagain"); if (Newpassword.equals (Newpasswordagain)) { Db.modify ("Update usertable set PAssword=? Where Username=? ", newpassword,username); errmsg =" Password modified successfully! " "; Request.setattribute (" ErrMsg ", errmsg); Request.getrequestdispatcher ("/form.jsp "). Forward (request,response);} else{errmsg = "Two times input password inconsistent!" "; Request.setattribute (" ErrMsg ", errmsg); Request.getrequestdispatcher ("/form.jsp "). Forward (request,response);}} else {errmsg = "bad password!" "; Request.setattribute (" ErrMsg ", errmsg); Request.getrequestdispatcher ("/form.jsp "). Forward (request,response);}} else {errmsg = "user name does not exist! "; Request.setattribute (" ErrMsg ", errmsg); Request.getrequestdispatcher ("/form.jsp "). Forward (request,response);}} catch (Exception e) {e.printstacktrace ();}}}

Iv. Summary and Prospect

From the above introduction, you can see the advantages and disadvantages of MVC, the code of this thing more than usual, and more layered, build a durable layer, That is Dbdao.java thinking, but after you hit the foundation of M, you want to add a new function, you just add things in Web. XML, plus the C layer of Java, query the database statement unified into a few methods query,insert,modify, connect the database, Shutting down the database doesn't have to be done. Rather than a new programming model, the idea of object-oriented OO programming is further deepened. This requires you to be more familiar with the transfer of variables.

"Servlet" Design user login, user registration, Change password system according to MVC idea

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.