Javaweb implements the user login registration function instance code (based on Servlet+jsp+javabean mode) _java

Source: Internet
Author: User
Tags locale pack uuid xpath

The following through an illustrated way to introduce Javaweb to implement the user login registration function Instance code, take a look at it.

Introduction of Servlet+jsp+javabean development model (MVC)

Servlet+jsp+javabean mode (MVC) is suitable for the development of complex web applications, in which the servlet handles user requests, JSP is responsible for data display, and JavaBean is responsible for encapsulating the data. Servlet+jsp+javabean mode program Each module between the level of clear, Web development recommended this model.

Here with a most commonly used user login registration program to explain the Servlet+jsp+javabean development model, through the user Login registration procedure synthesis case, the previous learned XML, Xpath, Servlet, JSP knowledge points are concatenated.

Ii. creating a Web project for the MVC architecture

Create a new Webmvcframework project in MyEclipse, import the development Kit (jar package) that the project needs, create the packages that the project needs, and in Java development, the architecture is in the form of a package

The development package (jar package) required by the project
Serial number Development Package Name Describe
1 Dom4j-1.6.1.jar dom4j for manipulating XML files
2 Jaxen-1.1-beta-6.jar Used to parse an XPath expression
3 Commons-beanutils-1.8.0.jar Tool classes, for processing bean objects
4 Commons-logging.jar Commons-beanutils-1.8.0.jar -dependent Jar pack
5 Jstl.jar Jstl Tag Library and El expression dependency pack
6 Standard.jar Jstl Tag Library and El expression dependency pack

A good JAVAWEB project structure should have more than 11 packages, so that the level of clarity, the responsibilities between the various layers are very clear, to build Javaweb project structure, according to the above 1~ 11 ordinal order to create the package: Domain→dao→dao.impl→service→service.impl→web.controller→web.ui→web.filter→web.listener→util→junit.test, package hierarchy created well , the structure of the project has been set up, of course, in the actual project development, it is not necessarily completely in accordance with

The package required by the project
Serial number Package Name Describe Subordinate hierarchy
1 Me.gacl.domain The JavaBean class that holds the system (containing only simple attributes and the corresponding get and set methods for attributes, without specific business processing methods) is provided to the data access layer, the business processing layer, and the Web layer to use domain (field model) layer
2 Me.gacl. Dao The operator interface class that holds access to the database Data Access Layer
3 Me.gacl. Dao.impl The implementation class that holds the operation interface for accessing the database
4 Me.gacl. Service Storage Processing System Business Interface class Business Processing Layer
5 Me.gacl. Service.impl The implementation class of the business interface of the storage processing system
6 Me.gacl. Web.controller A servlet that holds as a system controller Web layer (presentation layer)
7 Me.gacl. Web. Ui A servlet (UI refers to the user interface) that provides your user interface
8 Me.gacl.web.filter The filter used to store the system (filter)
9 Me.gacl.web.listener To store the system's used listeners (Listener)
10 me.gacl. util A generic tool class for the system , provided to the data access layer, the business process layer, the Web layer to use
11 Junit.test Test classes for storing systems

It says to create a hierarchy of packages, but depending on the actual situation of the project, you might also need to create its

His bag, it's got to be based on the needs of the project.

Under the SRC directory (class directory), create an XML file to hold user data (Db.xml)

Create a pages directory in the Web-inf directory, pages directory to store the system of some protected (not allow users directly through the URL address) JSP page, users want to access these protected JSP pages, then only through the Me.gacl.web.UI the servlet inside the bag

The created items are shown in the following figure (Figure 1):

  

Figure-1

Code writing for layered architecture

The code for layered schemas is also followed by the "Domain model layer (domains)" → "Data access layer (DAO, dao.impl)" → "Business processing layer (service, service.impl)" → "Presentation layer (Web.controller, web. UI, Web.filter, Web.listener) "→" Tool class (Util) → "test Class (Junit.test)" in order to write.

3.1, the development of domain layer

Create a user class under the Me.gacl.domain package

  

The user class specific code is as follows:

Package me.gacl.domain;
Import java.io.Serializable;
Import java.util.Date;
/**
* @author gacl
* User entity class * * Public
class user implements Serializable {
private static final long SE Rialversionuid =-L;
User ID
private String ID;
User name
private String userName;
User Password
private String userpwd;
User Mailbox
private String email;
User Birthday
private Date birthday;
Public String GetId () {return
ID;
}
public void SetId (String id) {
this.id = ID;
}
Public String GetUserName () {return
userName;
}
public void Setusername (String userName) {
this.username = userName;
}
Public String getuserpwd () {return
userpwd;
}
public void Setuserpwd (String userpwd) {
this.userpwd = userpwd;
}
Public String Getemail () {return
email;
}
public void Setemail (String email) {
This.email = email;
}
Public Date Getbirthday () {return
birthday;
}
public void Setbirthday (Date birthday) {
this.birthday = birthday;
}
}

3.2, the development of data Access Layer (DAO, Dao.impl)

Create a Iuserdao interface class under the Me.gacl.dao package, for the development of the interface class, I am accustomed to the letter I as a class prefix, so that a glimpse of the current class is an interface, which is a good development habits, by looking at the class name can easily distinguish between the interface or the specific implementation class.

  

The specific code for the Iuserdao interface is as follows:

Package Me.gacl.dao;
Import Me.gacl.domain.User;
Public interface Iuserdao {
/**
* To find users based on user name and password
* @param userName
* @param userpwd
* @return users found c9/>*/
User Find (String userName, String userpwd);
/**
* Add Users
* @param user
/
void Add (username);
/** the user name to find users
* @param userName
* @return The user found * *
(String userName);

For the definition of the method in the interface, this can only be based on the specific business to analyze what needs to be defined, but no matter how complex the business, can not be separated from the basic crud (incremental Search) operations, the DAO layer is directly interacting with the database, Therefore, the DAO layer interface will generally have an increase in the search for these four kinds of operations related methods.

Create a Userdaoimpl class under the Me.gacl.dao.impl package

  

Userdaoimpl class is the Iuserdao interface of the specific implementation class, for the implementation of the interface naming method, I am accustomed to "interface name (remove prefix i) +impl" form or "Interface name +impl" form to name: Iuserdao (interface) →userdaoimpl (Implementation Class) or Iuserdao (interface) →iuserdaoimpl (Implementation Class), which is also considered some personal programming habits, usually see the code is mostly in these two forms to name the interface of the specific implementation class, Anyway is to be able to see the interface corresponding to the implementation of the class is what one can be.

The specific code for the Userdaoimpl class is as follows:

Package Me.gacl.dao.impl;
Import Java.text.SimpleDateFormat;
Import org.domj.Document;
Import org.domj.Element;
Import Me.gacl.dao.IUserDao;
Import Me.gacl.domain.User;
Import Me.gacl.util.XmlUtils; /** * Iuserdao Interface Implementation class * @author GaCl/public class Userdaoimpl implements Iuserdao {@Override public User find (String us Ername, String userpwd) {try{Document document = Xmlutils.getdocument ();//Use XPath expression to manipulate XML node Element e = (Element) docu
Ment.selectsinglenode ("//user[@userName = '" +username+ "' and @userPwd = '" +userpwd+ ")");
if (e==null) {return null;}
User user = new user ();
User.setid (E.attributevalue ("id"));
User.setemail (E.attributevalue ("email"));
User.setuserpwd (E.attributevalue ("userpwd"));
User.setusername (E.attributevalue ("UserName"));
String birth = e.attributevalue ("Birthday");
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd");
User.setbirthday (Sdf.parse (birth));
return user;
}catch (Exception e) {throw new RuntimeException (e);}} @SuppressWarnings ("deprecation") @OVerride public void Add (user user) {try{Document document = Xmlutils.getdocument ();
Element root = Document.getrootelement (); Element User_node = root.addelement ("user");
Create a user node and hang to root user_node.setattributevalue ("id", User.getid ());
User_node.setattributevalue ("UserName", User.getusername ());
User_node.setattributevalue ("Userpwd", User.getuserpwd ());
User_node.setattributevalue ("Email", user.getemail ());
SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd");
User_node.setattributevalue ("Birthday", Sdf.format (User.getbirthday ()));
Xmlutils.writexml (document);
}catch (Exception e) {throw new RuntimeException (e);}}
@Override public User Find (String userName) {try{Document document = Xmlutils.getdocument ();
Element e = (Element) Document.selectsinglenode ("//user[@userName = '" +username+ "]");
if (e==null) {return null;}
User user = new user ();
User.setid (E.attributevalue ("id"));
User.setemail (E.attributevalue ("email"));
User.setuserpwd (E.attributevalue ("userpwd")); User.setuseRname (E.attributevalue ("UserName"));
String birth = e.attributevalue ("Birthday");
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd");
User.setbirthday (Sdf.parse (birth));
return user;
}catch (Exception e) {throw new RuntimeException (e);}} }

3.3, the Development of service layer (service layer to the Web layer to provide all business services)

Creating the Iuserservice interface class in the Me.gacl.service package

The specific code for the Iuserservice interface is as follows:

Package me.gacl.service;
Import Me.gacl.domain.User;
Import me.gacl.exception.UserExistException;
Public interface Iuserservice {
/**
* provides registration service
* @param user
* @throws userexistexception
* * void RegisterUser (user user) throws userexistexception;
/** *
provides login service
* @param userName
* @param userpwd
* @return
/User Loginuser (String UserName, String userpwd);

Create Userserviceimpl class in Me.gacl.service.impl package

The Userserviceimpl class is the concrete implementation class for the Iuserservice interface, the specific code is as follows:

Package Me.gacl.service.impl;
Import Me.gacl.dao.IUserDao;
Import Me.gacl.dao.impl.UserDaoImpl;
Import Me.gacl.domain.User;
Import me.gacl.exception.UserExistException;
Import Me.gacl.service.IUserService;
public class Userserviceimpl implements Iuserservice {
private Iuserdao Userdao = new Userdaoimpl ();
@Override public
void RegisterUser (user user) throws Userexistexception {
if (Userdao.find user.getusername ( )!=null) {
//checked exception 
//unchecked exception
//The reason for the compile-time exception is thrown: I want to have a layer of program handle this exception to give the user a friendly hint
throw new Userexistexception ("Registered user name already exists!!! ");
}
Userdao.add (user);
}
@Override public
User loginuser (String userName, String userpwd) {return
userdao.find (UserName, userpwd); c21/>}
}

3.4, the development of the Web layer

3.4.1, Development registration function

1, under the Me.gacl.web.UI package to write a registeruiservlet to provide users with the registration interface

When Registeruiservlet receives a user request, it jumps to the register.jsp

The code for Registeruiservlet is as follows:

Package Me.gacl.web.UI;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
/**
* @author gacl
* a servlet * Registeruiservlet for users to provide a registered user interface is
responsible for user output registration interface
* When a user accesses a Registeruiservlet , you jump to the register.jsp page in the Web-inf/pages directory/public
class Registeruiservlet extends HttpServlet {public
void Doget (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
request.getrequestdispatcher ("/web-inf/pages/register.jsp"). Forward (request, response);
public void DoPost (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
doget (request, response);
}
}

2, in the/web-inf/pages/directory to write user-registered JSP page register.jsp

    

The JSP pages located in the Web-inf directory cannot be directly accessed directly through the URL address,

    

In development, if you have some sensitive Web resources in your project that you do not want to be accessed directly from the outside world, consider placing these sensitive Web resources in the Web-inf directory so that you can prevent the outside world from accessing them directly via URLs.

The code for the Register.jsp page is as follows:

<%@ page language= "java" pageencoding= "utf-"%> <! DOCTYPE html> <html> <head> <title> User Registration </title> </head> <body style= "Text-align: Center; " > <form action= "${pagecontext.request.contextpath}/servlet/registerservlet" method= "POST" > <table width = "%" border= "" > <tr> <td> User name </td> <td> <input type= "text" name= "UserName" > </td > </tr> <tr> <td> password </td> <td> <input type= "password" name= "Userpwd" > </td > </tr> <tr> <td> Confirm password </td> <td> <input type= "password" name= "Confirmpwd" > </
Td> </tr> <tr> <td> mailbox </td> <td> <input type= "text" name= "email" > </td> </tr> <tr> <td> Birthday </td> <td> <input type= "text" name= "Birthday" > </td> </ tr> <tr> <td> <input type= "reset" value= "Empty" > </td> <td> <input type= "Submit" value=Registration > </td> </tr> </table> </form> </body> </html> 

<form action= "${pagecontext.request.contextpath}/servlet/registerservlet" method= "post" in Register.jsp > Specify the form submission and give it to registerservlet for processing

3, under the Me.gacl.web.controller package for processing user Registration Registerservlet

Registerservlet is responsible for the following responsibilities:

1. Receive the form data that the client submits to the server.

2, verify the legality of the form data, if the checksum fails to jump back to register.jsp, and echo the error message.

3, if the validation pass, call the service layer to the database to register users.

In order to facilitate registerservlet receive form data and verify form data, here I design a registration form to verify the data Registerformbean, and then write the Webutils tool class, packaging client-submitted form data to Formbean.

Create a Me.gacl.web.formbean package to validate the registration form data Registerformbean

  

The Registerformbean code is as follows:

Package Me.gacl.web.formbean;
Import Java.util.HashMap;
Import Java.util.Map;
Import Org.apache.commons.beanutils.locale.converters.DateLocaleConverter; /** * Encapsulates a user registration form bean that is used to receive the value of a form entry in register.jsp the property in Registerformbean corresponds to the name one by one of the form entry in register.jsp * Registerformbean's duties, in addition to receiving the value of the form entry in register.jsp, is the legality of validating the value of the form entry * @author GACL */public class Registerformbean {// The properties in Registerformbean correspond to the name one by one of the form entry in register.jsp//&lt;input type= "text" name= "UserName"/&gt; Private String
UserName;
&lt;input type= "Password" name= "userpwd"/&gt; Private String userpwd;
&lt;input type= "Password" name= "confirmpwd"/&gt; Private String confirmpwd;
&lt;input type= "text" name= "email"/&gt; private String email;
&lt;input type= "text" name= "Birthday"/&gt; Private String birthday;
/** * The error message to the user when the checksum is not passed * * Private map&lt;string, string&gt; errors = new hashmap&lt;string, string&gt; (); Public map&lt;string, String&gt; geterrors () {return errors.} public void Seterrors (map&lt;string, string&gt; errors) {this.errors = errors}/* Validate method is responsible for validating form entry * Form entry validation rule: * Private String userName; User name cannot be empty, and if-the letter Abcdabcd * Private String userpwd; The password cannot be empty, and if-the number * private String confirmpwd; Two times password to be consistent * private String email; Can be empty, not empty if a valid mailbox * private String birthday; can be null, not empty, if a valid date */public Boolean validate () {Boolean isOk = true; if (This.username = null | | This.userName.trim ().
Equals ("")) {isOk = false; Errors.put ("UserName", "User name cannot be empty!!") ");
} else {if (!this.username.matches ("[A-za-z]{,}")) {isOk = false; Errors.put ("UserName", "username must be-bit letter!!
");
}
}
if (this.userpwd = null | | This.userPwd.trim (). Equals ("")) {isOk = false; Errors.put ("Userpwd", "Password cannot be empty!!") ");
} else {if (!this.userpwd.matches ("\\d{,}")) {isOk = false; Errors.put ("Userpwd", "Password must be-bit number!!")
");
}
} private String password;  Two times password to be consistent if (this.confirmpwd!= null) {if (!this.confirmpwd.equals (this.userpwd)) {isOk = false; Errors.put ("Confirmpwd", "Two times password inconsistent!!"
");
}
} Private String Email; Can be empty, not empty if a legal mailbox
if (this.email!= null &amp;&amp;!this.email.trim (). Equals ("")) {if (!this.email.matches ("\\w+@\\w+ (\\.\\w+) +")) {IsO
K = false; Errors.put ("Email", "Mailbox is not a legal mailbox!!")
");
}
} Private String birthday; can be null, not empty, if a valid date if (this.birthday!= null &amp;&amp;!this.birthday.trim (). Equals ("")) {try {Datelocaleconverter Co
Nver = new Datelocaleconverter ();
Conver.convert (This.birthday); catch (Exception e) {isOk = false; Errors.put ("Birthday", "Birthday must be a date!!")
");
}
}
return isOk; 
Public String GetUserName () {return userName.} public void Setusername (String userName) {this.username = UserName;} Public String getuserpwd () {return userpwd.} public void Setuserpwd (String userpwd) {this.userpwd = userpwd; 
String Getconfirmpwd () {return confirmpwd.} public void Setconfirmpwd (string confirmpwd) {this.confirmpwd = confirmpwd; public string Getemail () {return e-mail;} public void Setemail (String email) {this.email = email; Birthday () {return birthday;}
public void Setbirthday (String birthday) {this.birthday = birthday;}} 

Create a Webutils tool class under the Me.gacl.util package that encapsulates client-submitted form data into Formbean

Package me.gacl.util;
Import java.util.Enumeration;
Import Java.util.UUID;
Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.commons.beanutils.BeanUtils;
/**
* @author gacl
* Encapsulates the request parameters in the requested object into the bean */public
class Webutils {
/**
* Convert Request object to T object
* @param request 
* @param clazz
* @return/public
static <T> T Requestbean (httpservletrequest request,class<t> clazz) {
try{
T bean = clazz.newinstance ();
Enumeration<string> e = Request.getparameternames (); 
while (E.hasmoreelements ()) {
String name = (String) e.nextelement ();
String value = request.getparameter (name);
Beanutils.setproperty (bean, name, value);
}
return bean;
catch (Exception e) {
throw new RuntimeException (e);
}
}
/**
* Generate UUID
* @return
/public static String Makeid () {return
uuid.randomuuid (). ToString ( );
}
}

Finally, take a look at the Registerservlet complete code that handles user registration:

Package Me.gacl.web.controller;
Import java.io.IOException;
Import Java.util.Date;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.beanutils.BeanUtils;
Import Org.apache.commons.beanutils.ConvertUtils;
Import Org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
Import Me.gacl.domain.User;
Import me.gacl.exception.UserExistException;
Import Me.gacl.service.IUserService;
Import Me.gacl.service.impl.UserServiceImpl;
Import Me.gacl.util.WebUtils;
Import Me.gacl.web.formbean.RegisterFormBean; /** * Process User registered servlet * @author GACL */public class Registerservlet extends HttpServlet {public void doget (HTTPSERVLETR Equest request, HttpServletResponse response) throws Servletexception, IOException {// Encapsulate the client-submitted form data into the Registerformbean object Registerformbean Formbean = Webutils.requestbean (Request,registerformbean.class)
; Verify the form data that the user registers to fill out IF (formbean.validate () = False) {//if validation fails//Formbean object that encapsulates the user-filled form data is sent back to register.jsp page in form forms
Request.setattribute ("Formbean", Formbean); Checksum failure indicates that there is a problem with the form data that the user fills out, then jump back to register.jsp request.getrequestdispatcher ("/web-inf/pages/register.jsp"). Forward (
request, response);
Return
User user = new user ();
try {//register string to date Converter Convertutils.register (new Datelocaleconverter (), date.class);
Beanutils.copyproperties (user, Formbean);//Fill the form's data into the JavaBean User.setid (Webutils.makeid ());/Set the user's id attribute
Iuserservice service = new Userserviceimpl ();
Call the service layer provided by the registered User Services to achieve user registration Service.registeruser (users); String message = String.Format ("Registration successful!!") Seconds to automatically jump to the login page for you!!
&lt;meta http-equiv= ' refresh ' content= '; url=%s '/&gt; ', request.getcontextpath () + "/servlet/loginuiservlet");
Request.setattribute ("message", message);
Request.getrequestdispatcher ("/message.jsp"). Forward (Request,response); catch (Userexistexception e) {formbean.geterrors (). Put ("UserName", "Registered user already exists!!")
");
Request.setattribute ("Formbean", Formbean);Request.getrequestdispatcher ("/web-inf/pages/register.jsp"). Forward (request, response); catch (Exception e) {e.printstacktrace ();/////////////////////////////////L
");
Request.getrequestdispatcher ("/message.jsp"). Forward (Request,response); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {do
Get (request, response); }
}

If the form data checksum is not passed when the user registers, the server side stores a Formbean object that stores the error message and form data into the request object. And then send it back to the register.jsp page, so we need to remove the Formbean object from the Request object in the Register.jsp page, and then return the form data that the user filled out to the corresponding table item, and display the message to the form form when the error occurs, letting the user know what Data filling is illegal!

Modify the Register.jsp page with the following code:

&lt;%@ page language= "java" pageencoding= "utf-"%&gt; &lt;! DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; User Registration &lt;/title&gt; &lt;/head&gt; &lt;body style= "Text-align: Center; " &gt; &lt;form action= "${pagecontext.request.contextpath}/servlet/registerservlet" method= "POST" &gt; &lt;table width = "%" border= "" &gt; &lt;tr&gt; &lt;td&gt; User name &lt;/td&gt; &lt;td&gt; &lt;%--using el expression ${} Extracts the form data (formbean.username) encapsulated in the Formbean object stored in the request object and the error message (formbean.errors.userName)--%&gt; &lt;input type= " Text "Name=" UserName "value=" ${formbean.username} "&gt;${formbean.errors.username} &lt;/td&gt; &lt;/tr&gt; &lt;tr &gt; &lt;td&gt; password &lt;/td&gt; &lt;td&gt; &lt;input type= "password" name= "userpwd" value= "${formbean.userpwd}" &gt;${ FORMBEAN.ERRORS.USERPWD} &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Confirm password &lt;/td&gt; &lt;td&gt; &lt;input type= " Password "name=" confirmpwd "value=" ${formbean.confirmpwd} "&gt;${formbean.errors.confirmpwd} &lt;/td&gt; &lt;/tr &gt; &lt;tr&gt; &lt;td&gt; mailbox &lt;/td&gt; &lt;td&gt; &lt;inPut type= "text" name= "email" value= "${formbean.email}" &gt;${formbean.errors.email} &lt;/td&gt; &lt;/tr&gt; &lt;tr &gt; &lt;td&gt; birthday &lt;/td&gt; &lt;td&gt; &lt;input type= "text" name= "Birthday" value= "${formbean.birthday}" &gt;${ Formbean.errors.birthday} &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;input type= "reset" value= "Empty" &gt; &lt;/td &gt; &lt;td&gt; &lt;input type= "Submit" value= "registration" &gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/body &gt; &lt;/html&gt;

To this end, the user registration function is a development completed!

The following test the development of a good user registration function:

Enter URL address: Http://localhost:8080/webmvcframework/servlet/RegisterUIServlet access to register.jsp page, the effect is as follows:

    

If you enter a table item that does not conform to the checksum rule, it cannot be registered and the effect is as follows:

    

3.4.2, Development login function

1, under the Me.gacl.web.UI package to write a loginuiservlet to provide users with login interface

  

When Loginuiservlet receives a user request, it jumps to the login.jsp

The code for Loginuiservlet is as follows:

Package Me.gacl.web.UI;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
/**
* @author gacl
* Loginuiservlet is responsible for user output login interface
* When the user accesses the Loginuiservlet, it jumps to the Web-inf/pages page under the login.jsp directory
*
/public class Loginuiservlet extends HttpServlet {public
void doget (HttpServletRequest request, HttpServletResponse response)
throws Servletexception, IOException {
request.getrequestdispatcher ("/ Web-inf/pages/login.jsp "). Forward (request, response);
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
doget (request, response);
}
}

2, in the/web-inf/pages/directory to write user login JSP page login.jsp

  

The code for the Login.jsp page is as follows:

<%@ page language= "java" pageencoding= "utf-"%>
<! DOCTYPE html>
 
 

login.jsp <form action= "${pagecontext.request.contextpath}/servlet/loginservlet" method= "POST" > Specify that the form is submitted, Handed to loginservlet for processing.

3, under the Me.gacl.web.controller package for processing user login Loginservlet

The code for Loginservlet is as follows:

Package Me.gacl.web.controller;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Me.gacl.domain.User;
Import Me.gacl.service.IUserService;
Import Me.gacl.service.impl.UserServiceImpl; /** * Process User Login servlet * @author GACL */public class Loginservlet extends HttpServlet {public void doget (httpservletrequ EST request, httpservletresponse response) throws Servletexception, IOException {//Get user-filled login username String username = Request
. GetParameter ("username");
Get user-filled login password String password = request.getparameter ("password");
Iuserservice service = new Userserviceimpl ();
User Login username = service.loginuser (username, password); if (user==null) {String message = String.Format ("Sorry, wrong username or password!!") Please login again! Seconds to automatically jump to the login page for you!!
&lt;meta http-equiv= ' refresh ' content= '; url=%s ' ", Request.getcontextpath () +"/servlet/loginuiservlet "); Request.setattribute ("Message", message);
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response);
Return
After the login is successful, the user is stored in the session request.getsession (). setattribute ("user", user); String message = String.Format ("Congratulations:%s, login successful!") This page will jump to the home page in seconds!!
&lt;meta http-equiv= ' refresh ' content= '; url=%s ' ", User.getusername (), Request.getcontextpath () +"/index.jsp ");
Request.setattribute ("message", message);
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {DoG
ET (request, response); }
}

In this, the user login function is a development completed.

The following test to develop a good user login function, input URL address: Http://localhost:8080/webmvcframework/servlet/LoginUIServlet access to login.jsp page, enter the correct username and password to login, the effect is as follows:

  

If you enter a wrong username and password, you will not be able to log on successfully and the effect is as follows:

  

3.4.3, Development logoff feature

Write a logoutservlet that handles user logoff under the Me.gacl.web.controller package

The code for Logoutservlet is as follows:

Package Me.gacl.web.controller;
Import java.io.IOException;
Import Java.text.MessageFormat;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; public class Logoutservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respon SE) throws Servletexception, IOException {//Remove user object stored in session, implement logoff feature Request.getsession (). RemoveAttribute ("User"
);
Because the string contains single quotes, there is a problem in this case when the string is spliced using the Messageformat.format method//messageformat.format method simply removes the single quotation mark from the string and does not populate the specified placeholder String TempStr = Messageformat.format ("Logout successful!!") Seconds to automatically jump to the login page for you!!
&lt;meta http-equiv= ' refresh ' content= '; url={} '/&gt; ', request.getcontextpath () + "/servlet/loginuiservlet"); SYSTEM.OUT.PRINTLN (TEMPSTR)//Output Result: Logout success!! Seconds to automatically jump to the login page for you!! &lt;meta Http-equiv=refresh content=;url={}/&gt; System.out.println ("--------------------------------------------
-------------"); /** * To solve "if the string to be spliced contains single quotes, then meThe Ssageformat.format method simply removes the single quotation mark from the string and does not populate the specified placeholder with the question, * then you can use a single quote in a string enclosed in single quotes, for example: "&lt;meta http-equiv=" ' Refresh ' ' content= '; url={} '/&gt; ' Messageformat.format ("&lt;meta http-equiv= ' ' Refresh '" ' content= '; url={} ') &gt; "," index.jsp ") can return normally * &lt;meta http-equiv= ' refresh ' content= '; url=index.jsp '/&gt; */String TempStr = Messageformat.format ("Logout success!!) Seconds to automatically jump to the login page for you!!
&lt;meta http-equiv= ' refresh ' content= '; url={} '/&gt; ', request.getcontextpath () + "/servlet/loginuiservlet"); /** * Output Result: * Logout success!!
Seconds to automatically jump to the login page for you!! * &lt;meta http-equiv= ' refresh ' content= '; Url=/webmvcframework/servlet/loginuiservlet '/&gt; * * SYSTEM.OUT.PRINTLN (
TEMPSTR); String message = String.Format ("Logout successful!!") Seconds to automatically jump to the login page for you!!
&lt;meta http-equiv= ' refresh ' content= '; url=%s '/&gt; ', request.getcontextpath () + "/servlet/loginuiservlet");
Request.setattribute ("message", message);
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); public void DoPost (HttpServletRequest request, HttpServletResponse REsponse) throws Servletexception, IOException {doget (request, response);} 

After the user log in successfully, the logged in user information will be stored in the session, so we want to delete the user stored in the session, so that users can log off.

After a successful user login will jump to the index.jsp page, in the index.jsp page put a "Quit Landing" button, when clicked "Exit Login" button, on the access to Logoutservlet, the user log off.

The code for INDEX.JSP is as follows:

 <%@ page language= "java" pageencoding= "utf-"%> <%--to avoid the presence of Java code in JSP pages,
This introduces the JSTL tag library, using JSTL tag library to do some logical judgment processing--%> <%@ taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%> <!
DOCTYPE html>  
 

Test the development of a good logoff function, the effect is as follows:

  

In this, all the functions have been developed and the test passed.

Iv. Summary of development

Through this small example, you can understand the MVC layered architecture of the project, in peacetime project development, also in the following order to develop:

  1, build the development environment

1.1 Creating a Web project

1.2 The development package required to import the project

1.3 Create the package name of the program, in Java, a package to reflect the hierarchical structure of the project

 2, the development of domain

Take a table to be manipulated as a Vo class (The Vo class defines only the properties and the get and set methods of the attributes). There is no operational method involved in the specific business, VO is the value object, in layman's sense, is to take every record in the table as an object, each field in the table as a property of this object. Inserting a record into a table is equivalent to inserting an instance object of a Vo class into a datasheet, and when manipulating a data table, the object of a Vo class is written directly into the table, and a Vo object is a record. Each Vo object can represent a single row of records in a table, and the name of the Vo class is consistent with or corresponds to the name of the table.

  3. Develop DAO

3.1 DAO operator interface: Each DAO operating interface specifies how a table is used in a project, and the name of this interface is best written in the following format: "I table name DAO".

All the methods inside the ├dao interface are written according to the following naming:

├ Update Database: Doxxx ()

├ Query Database: findxxx () or getxxx ()

3.2 DAO operation interface Implementation class: implementation class to complete specific additions and deletions to check operations

├ This implementation class completes only the core operations of the database and does not specifically handle the opening and closing of the database, as these operations are independent of the specific business operations.

  4, Development Service (service to the Web layer to provide all business services)

  5, the development of the Web layer

The above content is small series to introduce the Javaweb implementation of user login registration function instance code (based on Servlet+jsp+javabean mode), hope to help everyone!

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.