Below, we will introduce the example code of JavaWeb to implement user login and registration function through pictures and texts. Let’s take a look.
1. Introduction to Servlet+JSP+JavaBean Development Model (MVC)
Servlet+JSP+JavaBean mode (MVC) is suitable for developing complex web applications. In this mode, servlets are responsible for processing user requests, jsp is responsible for data display, and javabean is responsible for encapsulating data. The Servlet+JSP+JavaBean mode program has clear levels between the modules, and web development is recommended to use this mode.
Here we use the most commonly used user login registration program to explain the Servlet+JSP+JavaBean development model. Through this user login registration program comprehensive cases, we connect the knowledge points of XML, Xpath, Servlet, and jsp that we have learned before.
2. Create a web project with MVC architecture
Create a new webmvcframework project in MyEclipse, import the development package (jar package) required by the project, and create the packages required by the project. In Java development, the architecture level is reflected in the form of a package
| Development packages (jar packages) required by the project | ||
| Serial number | Development Package Name | describe |
| 1 | dom4j-1.6.1.jar | dom4j is used to manipulate XML files |
| 2 | jaxen-1.1-beta-6.jar | Used to parse XPath expressions |
| 3 | commons-beanutils-1.8.0.jar | Tool class for processing bean objects |
| 4 | commons-logging.jar | Commons-beanutils-1.8.0.jar dependency jar package |
| 5 | jstl.jar | jstl tag library and EL expression dependency package |
| 6 | standard.jar | jstl tag library and EL expression dependency package |
A good JavaWeb project architecture should have the above 11 packages, which makes it clear and the responsibilities between each layer clear. When building a JavaWeb project architecture, create the packages in the order of 1 to 11 above: domain→dao→dao.impl→service→service.impl→web.controller→web.UI→web.filter→web.listener→util→junit.test. Once the package level is created, the project architecture will be determined. Of course, in actual project development, it may not be completely based on
| Packages required for the project | |||
| Serial number | Package name | describe | Level |
| 1 | me.gacl.domain | The JavaBean class that stores the system (only contains simple attributes and get and set methods corresponding to the attributes, and does not include specific business processing methods), provided to [data access layer], [business processing layer], and [web layer] for use | domain(domain model) layer |
| 2 | me.gacl. dao | The operation interface class that stores access to the database | Data access layer |
| 3 | me.gacl. dao.impl | Implementation class that stores the operation interface that accesses the database | |
| 4 | me.gacl. service | Store processing system business interface class | Business Processing Layer |
| 5 | me.gacl. service.impl | Implementation class for storing processing system business interface | |
| 6 | me.gacl. web.controller | Servlets stored as system controller | Web layer (presentation layer) |
| 7 | me.gacl.web.UI | Servlets (UI refers to user interface) that provides user interface for users | |
| 8 | me.gacl.web.filter | Filter used for storage system | |
| 9 | me.gacl.web.listener | Listener used to store the system | |
| 10 | me.gacl .util | Common tools for storing the system, provided to [data access layer], [business processing layer], and [web layer] for use | |
| 11 | junit.test | Test class for storing the system | |
As mentioned above, we create a package hierarchy, but based on the actual situation of the project, we may also need to create it.
His bag, this depends on the project needs.
Under the src directory (category directory), create an xml file (DB.xml) for saving user data (DB.xml)
Create a pages directory in the WEB-INF directory. The pages directory stores some protected jsp pages of the system (not allowing users to access directly through URL addresses). If users want to access these protected jsp pages, they can only use the Servlet in the me.gacl.web.UI package
The created project is shown in the following figure (Figure-1):
Figure-1
3. Code writing of hierarchical architecture
The code of the hierarchical architecture is also written in the order of [Domain Model Layer (domain)] → [Data Access Layer (dao, dao.impl)] → [Business Processing Layer (service, service.impl)] → [Expression Layer (web.controller, web.UI, web.filter, web.listener)] → [Tool Class (util)] → [test Class (junit.test)].
3.1. Develop domain layer
Create a User class under the me.gacl.domain package
The specific code of the User class 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 serialVersionUID = -L;// User IDprivate String id;// User name private String userName;// User password private String userPwd;// User email 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. Develop data access layer (dao, dao.impl)
Create an IUserDao interface class under the me.gacl.dao package. For development interface classes, I am used to using the letter I as the prefix of the class, so that you can see at a glance that the current class is an interface, which is also a good development habit. By looking at the class name, you can easily distinguish whether it is an interface or a specific implementation class.
The specific code of the IUserDao interface is as follows:
package me.gacl.dao;import me.gacl.domain.User;public interface IUserDao {/*** Find the user based on the user name and password* @param userName* @param userPwd* @return The user found*/User find(String userName, String userPwd);/*** Add user* @param user*/void add(User user);/** Find the user based on the user name* @param userName* @return The user found*/User find(String userName);}For the method definition in the interface, this can only analyze which methods need to be defined based on the specific business. However, no matter how complex the business is, it cannot be separated from the basic CRUD (addition, deletion, modification and query) operation. The Dao layer directly interacts with the database, so the Dao layer interface generally has four related methods for adding, deletion, modification and query.
Create a UserDaoImpl class under the me.gacl.dao.impl package
The UserDaoImpl class is a specific implementation class of the IUserDao interface. For the naming method of the implementation class of the interface, I am used to naming it in the form of "interface name (remove the prefix I) + impl" or "interface name + impl": IUserDao(interface) → UserDaoImpl(implement class) or IUserDao(interface) → IUserDaoImpl(implement class). This is also a personal programming habit. Most of the code I see usually names the specific implementation class of the interface in one of these two forms. Anyway, you need to be able to see which implementation class corresponding to the interface is at a glance.
The specific code of 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;/*** Implementation class of IUserDao interface* @author gacl*/public class UserDaoImpl implements IUserDao {@Overridepublic User find(String userName, String userPwd) {try{Document document = XmlUtils.getDocument();//Use XPath expression to manipulate XML nodesElement e = (Element) document.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")@Overridepublic void add(User user) {try{Document document = XmlUtils.getDocument();Element root = document.getRootElement();Element user_node = root.addElement("user"); //Create user node and hang it to rootuser_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);}}@Overridepublic 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. Development service layer (the service layer provides all business services to the web layer)
Create the IUserService interface class in the me.gacl.service package
The specific code of the IUserService interface is as follows:
package me.gacl.service;import me.gacl.domain.User;import me.gacl.exception.UserExistException;public interface IUserService {/*** Provide registration service* @param user* @throws UserExistException*/void registerUser(User user) throws UserExistException;/*** Provide login service* @param userName* @param userPwd* @return*/User loginUser(String userName, String userPwd);}Create UserServiceImpl class in the me.gacl.service.impl package
The UserServiceImpl class is a specific implementation class of 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();@Overridepublic void registerUser(User user) throws UserExistException {if (userDao.find(user.getUserName())!=null) {//checked exception //unchecked exception//The reason for throwing compile-time exception here: I want the previous program to handle this exception to give the user a friendly prompt throw new UserExistException("The registered username already exists!!!");}userDao.add(user);}@Overridepublic User loginUser(String userName, String userPwd) {return userDao.find(userName, userPwd);}}3.4. Develop the web layer
3.4.1. Develop registration function
1. Write a RegisterUIServlet under the me.gacl.web.UI package to provide a registration interface for users
After receiving the user request, RegisterUIServlet jumps to register.jsp
The code of 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* Servlet that provides users with registered user interface* RegisterUIServlet is responsible for outputting the registration interface for users* When a user accesses the RegisterUIServlet, it jumps 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. Write a user registered jsp page register.jsp in the /WEB-INF/pages/ directory
Any jsp page located in the WEB-INF directory cannot be accessed directly through the URL address.
During development, if there are some sensitive web resources in the project that do not want to be directly accessed by the outside world, you can consider putting these sensitive web resources into the WEB-INF directory, so that the outside world can be prohibited from accessing directly through the URL.
The code of 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><tr><td>Username</td><td><input type="text" name="userName"></td></tr><tr><td>Password</td><td><input type="password" name="userPwd"></td></tr><td>Confirm password</td><td><input type="password" name="confirmPwd"></td></tr><tr><td>Email</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="Clear"></td><td><input type="submit" value="Register"></td></tr></table></form></body></html> <form action="${pageContext.request.contextPath}/servlet/RegisterServlet" method="post"> in register.jsp indicates that the form is submitted and handed over to the RegisterServlet for processing
3. Write a RegisterServlet for handling user registration under the me.gacl.web.controller package
RegisterServlet serves the following responsibilities:
1. Receive form data submitted by the client to the server.
2. Verify the legality of the form data. If the verification fails, jump back to register.jsp and echo the error message.
3. If the verification is passed, call the service layer to register the user with the database.
In order to facilitate the RegisterServlet to receive form data and verification form data, I designed a RegisterFormbean for verification of registration form data, and then wrote the WebUtils tool class to encapsulate the form data submitted by the client into the formbean.
Create a RegisterFormbean for verifying registration form data under the me.gacl.web.formbean package
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;/*** The encapsulated user registration form bean is used to receive the value of the form input item in register.jsp* The attributes in the RegisterFormBean correspond to the name of the form input item in register.jsp* The responsibilities of the RegisterFormBean are not only responsible for receiving the value of the form input item in register.jsp, but also serve as the legality of the value of the form input item* @author gacl**/public class RegisterFormBean {//The properties in the RegisterFormBean correspond to the name of the form input item in register.jsp one by one //<input type="text" name="userName"/> private String userName;//<input type="password" name="userPwd"/> private String userPwd;//<input type="password" name="confirmPwd"/> private String confirmPwd;//<input type="text" name="email"/> private String email;//<input type="text" name="birthday"/> private String birthday;/*** The error message to the user when the verification fails*/private Map<String, String> errors = new HashMap<String, String>();public Map<String, String> getErrors() {return errors;}public void setErrors(Map<String, String> errors) {this.errors = errors;}/** validate method is responsible for verifying form input items* Form input item verification rules: * private String userName; The user name cannot be empty, and if it is - letter abcdABcd * private String userPwd; Password cannot be empty, and if it is - the number * private String confirmPwd; the password must be the same as the two times * private String email; It can be empty, not empty If it is a legal mailbox* private String birthday; It can be empty, not empty, if it is a legal date*/public boolean validate() {boolean isOk = true;if (this.userName == null || this.userName.trim().equals("")) {isOk = false;errors.put("userName", "The username cannot be empty! ! ");} else {if (!this.userName.matches("[a-zA-Z]{,}")) {isOk = false;errors.put("userName", "The username must be a letter of the -bit!!");}}if (this.userPwd == null || this.userPwd.trim().equals("")) {isOk = false;errors.put("userPwd", "The password cannot be empty!!");} else {if (!this.userPwd.matches("//d{,}")) {isOk = false;errors.put("userPwd", "The password must be a number of -bits!!");}}// private String password; The passwords must be the same when the two times are (this.confirmPwd != null) {if (!this.confirmPwd.equals(this.userPwd)) {isOk = false;errors.put("confirmPwd", "The passwords are inconsistent when the two times are not null!!");}}// private String email; It can be empty, not null. If it is a legal email if (this.email != null && !this.email.trim().equals("")) {if (!this.email.matches("//w+@//w+(//w+)+")) {isOk = false;errors.put("email", "The mailbox is not a legal mailbox!!");}}// private String birthday; Can be empty, not empty, if it is a legal date if (this.birthday != null && !this.birthday.trim().equals("")) {try {DateLocaleConverter convert = new DateLocaleConverter();conver.convert(this.birthday);} catch (Exception e) {isOk = false;errors.put("birthday", "The 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;}public String getConfirmPwd() {return confirmPwd;}public void setConfirmPwd(String confirmPwd) {this.confirmPwd = confirmPwd;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}}Create a WebUtils tool class under the me.gacl.util package. The function of this tool class is to encapsulate the form data submitted by the client into the 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* Encapsulate the request parameters in the request object into bean*/public class WebUtils {/*** Convert the request object into a 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, let’s take a look at the complete code of RegisterServlet responsible for handling 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;/*** Servlet handles user registration* @author gacl**/public class RegisterServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//Encapsulate the form data submitted by the client into the RegisterFormBean object RegisterFormBean formbean = WebUtils.requestBean(request,RegisterFormBean.class);//Check the form data filled in by the user registration if (formbean.validate() == false) {//If the verification fails //Send the form object encapsulating the form data filled by the user back to the form form on the register.jsp page for display request.setAttribute("formbean", formbean);//The verification fails to indicate that there is a problem with the form data filled by the user, so jump back to register.jsprequest.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response);return;}User user = new User();try {//ConvertUtils.register(new DateLocaleConverter(), Date.class);BeanUtils.copyProperties(user, formbean);//Fill the form data into the javabean user.setId(WebUtils.makeId());//Set the user's Id property IUserService service = new UserServiceImpl();//Call the registered user service provided by the service layer to achieve user registration service.registerUser(user); String message = String.format("Registered successfully! ! It will automatically jump to the login page for you in seconds! ! <meta http-equiv='refresh' content=';url=%s'/>", 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(); // Record exception in the background request.setAttribute("message", "Sorry, registration failed!!");request.getRequestDispatcher("/message.jsp").forward(request,response);}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}If the verification of the form data filled in fails when the user registers, the server will store a formbean object with error message and form data into the request object, and then send it back to the register.jsp page. Therefore, we need to take out the formbean object in the request object from the register.jsp page, and then reapply the form data filled in by the user to the corresponding form item, and also display the prompt message when an error occurs on the form form, so that the user knows which data is illegal to fill in!
Modify the register.jsp page, the code 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><tr><td>Username</td><td><%--Use the EL expression ${} to extract form data encapsulated in the formbean object stored in the request object (formbean.userName) and error message (formbean.errors.userName)--%><input type="text" name="userName" value="${formbean.userName}">${formbean.errors.userName}</td></tr><tr><td>Password</td><td><input type="password" name="userPwd" value="${formbean.userPwd}">${formbean.errors.userPwd}</td></tr><tr><td>Confirm password</td><td><input type="password" name="confirmPwd" value="${formbean.confirmPwd}">${formbean.errors.confirmPwd}</td></tr><tr><td>Email</td><td><input type="text" name="email" value="${formbean.email}">${formbean.errors.email}</td></tr><tr><td>Birthday</td><td><input type="text" name="birthday" value="${formbean.birthday}">${formbean.errors.birthday}</td></tr><tr><td><input type="reset" value="Clear"></td><td><input type="submit" value="Register"></td></tr></table></form></body></html>At this point, the user registration function has been developed!
The following tests the developed user registration function:
Enter the URL address: http://localhost:8080/webmvcframework/servlet/RegisterUIServlet to access the register.jsp page, and the operation effect is as follows:
If the entered form item does not comply with the verification rules, it cannot be registered. The operation effect is as follows:
3.4.2. Develop login function
1. Write a LoginUIServlet under the me.gacl.web.UI package to provide users with a login interface.
After the LoginUIServlet receives the user request, it jumps to login.jsp
The code of 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.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** @author gacl* LoginUIServlet is responsible for outputting the login interface for users* When the user accesses the LoginUIServlet, it jumps to the login.jsp page in the WEB-INF/pages 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. Write the user login login.jsp page under /WEB-INF/pages/ directory
The code of the login.jsp page is as follows:
<%@ page language="java" pageEncoding="UTF-"%><!DOCTYPE HTML><html><head><title>User login</title></head><body><form action="${pageContext.request.contextPath }/servlet/LoginServlet" method="post">Username: <input type="text" name="username"><br/>Password: <input type="password" name="password"><br/><input type="submit" value="Login"></form></body></html> The <form action="${pageContext.request.contextPath}/servlet/LoginServlet" method="post"> in login.jsp indicates that the form is submitted and handed over to the LoginServlet for processing.
3. Write a LoginServlet for handling user login under the me.gacl.web.controller package
The code of 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;/*** servlet handles user login* @author gacl**/public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//Get the login username filled in by the user String username = request.getParameter("username");//Get the login password filled in by the user String password = request.getParameter("password");IUserService service = new UserServiceImpl();//User loginUser user = service.loginUser(username, password);if(user==null){String message = String.format("Sorry, the username or password is incorrect!! Please log in again! You will automatically jump to the login page in seconds!! <meta http-equiv='refresh' content=';url=%s'", request.getContextPath()+"/servlet/LoginUIServlet");request.setAttribute("message",message);request.getRequestDispatcher("/message.jsp").forward(request, response);return;}//After login is successful, the user is stored in the session request.getSession().setAttribute("user", user);String message = String.format("Congratulations: %s, login is successful! This page will jump to the homepage in seconds! ! <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 {doGet(request, response);}}At this point, the user login function has been completed.
Below, test the developed user login function, enter the URL address: http://localhost:8080/webmvcframework/servlet/LoginUIServlet to access the login.jsp page, enter the correct username and password to log in, the operation effect is as follows:
If the username and password entered are incorrect, then the login cannot be successfully logged in, and the operation effect is as follows:
3.4.3. Develop the cancel function
Write a LogoutServlet for handling user logout under the me.gacl.web.controller package
The code of 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 response)throws ServletException, IOException {//Remove the user object stored in the session to implement the logout function request.getSession().removeAttribute("user");//Because the string contains single quotes, there will be problems when using the MessageFormat.format method to splice the string in this case //MessageFormat.format method only removes the single quotes in the string and will not fill the content into the specified placeholder String tempStr = MessageFormat.format("Logout successfully!! Automatically jump to the login page in seconds!! <meta http-equiv='refresh' content=';url={}'/>", request.getContextPath()+"/servlet/LoginUIServlet");System.out.println(tempStr);//Output result: Logout successfully! ! It will automatically jump to the login page for you in seconds! ! <meta http-equiv=refresh content=;url={}/>System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- content='';url={}''/>","index.jsp") can return normally * <meta http-equiv=''refresh'' content='';url=index.jsp'/>*/String tempStr = MessageFormat.format("Login successfully!! It will automatically jump to the login page in seconds!! <meta http-equiv=''refresh'' content='';url={}''/>", request.getContextPath()+"/servlet/LoginUIServlet");/*** Output result: *Login successfully! ! It will automatically jump to the login page for you in seconds! ! * <meta http-equiv='refresh' content=';url=/webmvcframework/servlet/LoginUIServlet'//System.out.println(tempStr);String message = String.format("Logout successfully!! Automatically jump to the login page in seconds!! <meta http-equiv='refresh' content=';url=%s'/>", 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 logs in successfully, the logged-in user information will be stored in the session, so we need to delete the user stored in the session, so that the user can be logged out.
After the user logs in successfully, it will jump to the index.jsp page and put a [Login] button in the index.jsp page. When the [Login] button is clicked, you will access the LogoutServlet to log out of the user.
The code for index.jsp is as follows:
<%@ page language="java" pageEncoding="UTF-"%><%--In order to avoid the appearance of java code in jsp pages, the jstl tag library is introduced here, and the tags provided by the jstl tag library are used to do some logical judgment processing--%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML><html><head><title>Home</title><script type="text/javascript">function doLogout(){//Access LogoutServlet to log out the currently logged-in user window.location.href="${pageContext.request.contextPath}/servlet/LogoutServlet";}</script></head><body><h>The website of the arrogant wolf</h><hr/><c:if test="${user==null}"><a href="${pageContext.request.contextPath}/servlet/RegisterUIServlet" target="_blank">Register</a><a href="${pageContext.request.contextPath}/servlet/LoginUIServlet">Login</a></c:if><c:if test="${user!=null}">Welcome: ${user.userName}<input type="button" value="Loginout" onclick="doLogout()"></c:if><hr//</body></html>Test and develop the logout function, the effects are as follows:
At this point, all functions have been developed and the test has been passed.
4. Development summary
Through this small example, we can understand that the project construction of the MVC layered architecture is also developed in the following order in the usual project development:
1. Build a development environment
1.1 Creating a web project
1.2 Import the development package required for the project
1.3 Create the package name of the program, which uses packages to reflect the project's hierarchical architecture in Java
2. Develop domain
Treat a table to be operated as a VO class (VO class only defines the properties and get and set methods corresponding to the properties, and does not involve specific business operation methods). VO represents a value object. In layman's terms, it means treating each record in the table as an object, and each field in the table is used as an attribute of this object.每往表中插入一条记录,就相当于是把一个VO类的实例对象插入到数据表中,对数据表进行操作时,都是直接把一个VO类的对象写入到表中,一个VO类对象就是一条记录。每一个VO对象可以表示一张表中的一行记录,VO类的名称要和表的名称一致或者对应。
3、开发dao
3.1 DAO操作接口:每一个DAO操作接口规定了,一张表在一个项目中的具体操作方法,此接口的名称最好按照如下格式编写:“I表名称Dao”。
├DAO接口里面的所有方法按照以下的命名编写:
├更新数据库:doXxx()
├查询数据库:findXxx()或getXxx()
3.2 DAO操作接口的实现类:实现类中完成具体的增删改查操作
├此实现类完成的只是数据库中最核心的操作,并没有专门处理数据库的打开和关闭,因为这些操作与具体的业务操作无关。
4、开发service(service 对web层提供所有的业务服务)
5、开发web层
以上内容是小编给大家介绍的JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式),希望对大家有所帮助!