This article mainly analyzes the user module of the book mall for everyone, the specific content is as follows
1. Related Class Creation of User Module
domain: User
dao: UserDao
service: UserDao
web.servlet: UserServlet
2. User registration
2.1 Registration process
/jsps/user/regist.jsp -> UserServlet#regist() -> msg.jsp
2.2 Registration page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Register</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>Register</h1> <%-- 1. Show errors --> Field Error 2. Display exception error 3. Echo --%><p style="color: red; font-weight: 900">${msg }</p><form action="<c:url value='/UserServlet'/>" method="post"> <input type="hidden" name="method" value="regist"/> Username: <input type="text" name="username" value="${form.username }"/> <span style="color: red; font-weight: 900">${errors.username }</span> <br/> Password: <input type="password" name="password" value="${form.password }"/> <span style="color: red; font-weight: 900">${errors.password }</span> <br/> Email: <input type="text" name="email" value="${form.email }"/> <span style="color: red; font-weight: 900">${errors.email }</span> <br/> <input type="submit" value="Register"/></form> </body></html>2.3 UserServlet
User
/** * User's domain object*/public class User { /* * Corresponding database table*/ private String uid;// Primary key private String username;// Username private String password;// Password private String email;// Email private String code;// Activation code private boolean state;// Status (Activated and inactivated)BaseServlet
public class BaseServlet extends HttpServlet { /* * It will decide which method of this class is called based on the method in the request */ protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); res.setContentType("text/html;charset=utf-8"); try { // For example: http://localhost:8080/demo1/xxx?m=add String method = req.getParameter("method");// It is a method nameClass c = this.getClass(); Method m = c.getMethod(method, HttpServletRequest.class, HttpServletResponse.class); String result = (String) m.invoke(this, req, res); if(result != null && !result.isEmpty()) { req.getRequestDispatcher(result).forward(req, res); } } catch (Exception e) { throw new ServletException(e); } }}UserServlet
/** * User expression layer*/public class UserServlet extends BaseServlet { private UserService userService = new UserService(); /** * Exit function* @param request * @param response * @return * @throws ServletException * @throws IOException */ public String quit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().invalidate(); return "r:/index.jsp"; } public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Encapsulate form data into form* 2. Enter verification (no writing) * 3. Call service to complete activation* > Save error information, form to request, forward to login.jsp * 4. Save user information into session, and then redirect to index.jsp */ User form = CommonUtils.toBean(request.getParameterMap(), User.class); try { User user = userService.login(form); request.getSession().setAttribute("session_user", user); /* * Add a shopping cart to the user, that is, save a Cart object to the session*/ request.getSession().setAttribute("cart", new Cart()); return "r:/index.jsp"; } catch (UserException e) { request.setAttribute("msg", e.getMessage()); request.setAttribute("form", form); return "f:/jsps/user/login.jsp"; } } /** * Activation function* @param request * @param response * @return * @throws ServletException * @throws IOException */ public String active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get the parameter activation code* 2. Call the service method to complete the activation* > Save the exception information to the request domain and forward to msg.jsp * 3. Save the success information to the request domain and forward to msg.jsp */ String code = request.getParameter("code"); try { userService.active(code); request.setAttribute("msg", "Congratulations, you have successfully activated it! Please log in now! "); } catch (UserException e) { request.setAttribute("msg", e.getMessage()); } return "f:/jsps/msg.jsp"; } /** * Registration function* @param request * @param response * @return * @throws ServletException * @throws IOException */ public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Encapsulate form data into form object* 2. Complete: uid, code * 3. Enter verification* > Save error information, form to request field, forward to register.jsp * 4. Call the service method to complete the registration* > Save error information, form to request field, forward to register.jsp * 5. Send email* 6. Save successful information forward to msg.jsp */ // Encapsulate form data User form = CommonUtils.toBean(request.getParameterMap(), User.class); // Complete form.setUid(CommonUtils.uuid()); form.setCode(CommonUtils.uuid()) + CommonUtils.uuid()); /* * Enter verification* 1. Create a Map to encapsulate error information, where the key is the form field name and the value is the error message*/ Map<String,String> errors = new HashMap<String,String>(); /* * 2. Get the username, password, and email in the form for verification*/ String username = form.getUsername(); if(username == null || username.trim().isEmpty()) { errors.put("username", "The username cannot be empty!"); } else if(username.length() < 3 || username.length() > 10) { errors.put("username", "The username must be between 3 and 10! "); } String password = form.getPassword(); if(password == null || password.trim().isEmpty()) { errors.put("password", "Password cannot be empty!"); } else if(password.length() < 3 || password.length() > 10) { errors.put("password", "Password must be between 3~10!"); } String email = form.getEmail(); if(email == null || email.trim().isEmpty()) { errors.put("email", "Email cannot be empty!"); } else if(!email.matches("//w+@//w+//.//w+")) { errors.put("email", "Email format error!"); } /* * 3. Determine whether there is an error message*/ if(errors.size() > 0) { // 1. Save the error message// 2. Save form data// 3. Forward to regist.jsp request.setAttribute("errors", errors); request.setAttribute("form", form); return "f:/jsps/user/regist.jsp"; } /* * Call the service's regist() method */ try { userService.regist(form); } catch (UserException e) { /* * 1. Save exception information* 2. Save form * 3. Forward to regist.jsp */ request.setAttribute("msg", e.getMessage()); request.setAttribute("form", form); return "f:/jsps/user/regist.jsp"; } /* * Send an email* Prepare the configuration file! */ // Get the configuration file content Properties props = new Properties(); props.load(this.getClass().getClassLoader() .getResourceAsStream("email_template.properties")); String host = props.getProperty("host");//Get server host String uname = props.getProperty("uname");//Get username String pwd = props.getProperty("pwd");//Get password String from = props.getProperty("from");//Get sender String to = form.getEmail();//Get recipient String subject = props.getProperty("subject");//Get the subject String content = props.getProperty("content");//Get the mail content content = MessageFormat.format(content, form.getCode());//Replace {0} Session session = MailUtils.createSession(host, uname, pwd);//Get session Mail mail = new Mail(from, to, subject, content);//Create the mail object try { MailUtils.send(session, mail);//Send an email! } catch (MessagingException e) { } /* * 1. Save success information* 2. Forward to msg.jsp */ request.setAttribute("msg", "Congratulations, registration is successful! Please activate it in the email address immediately"); return "f:/jsps/msg.jsp"; }}2.4 UserService
/** * User business layer*/public class UserService { private UserDao userDao = new UserDao(); /** * Registration function* @param form */ public void registration(User form) throws UserException{ // Verify username User user = userDao.findByUsername(form.getUsername()); if(user != null) throw new UserException("The user name has been registered!"); // Verify email user = userDao.findByEmail(form.getEmail()); if(user != null) throw new UserException("Email has been registered!"); // Insert the user into the database userDao.add(form); } /** * Activation function* @throws UserException */ public void active(String code) throws UserException { /* * 1. Use code to query the database and get user */ User user = userDao.findByCode(code); /* * 2. If the user does not exist, it means that the activation code is wrong*/ if(user == null) throw new UserException("Activation code is invalid!"); /* * 3. Verify whether the user's status is inactive. If it is activated, it means it is a secondary activation and an exception is thrown*/ if(user.isState()) throw new UserException("You have been activated, don't activate it again unless you want to die!"); /* * 4. Modify the user's status*/ userDao.updateState(user.getUid(), true); } /** * Login function* @param form * @return * @throws UserException */ public User login(User form) throws UserException { /* * 1. Use username to query to get User * 2. If user is null, an exception is thrown (the user name does not exist) * 3. Compare the passwords of form and user. If different, an exception is thrown (the password is wrong) * 4. Check the user's status. If false, an exception is thrown (not activated yet) * 5. Return user */ User user = userDao.findByUsername(form.getUsername()); if(user == null) throw new UserException("The user name does not exist! "); if(!user.getPassword().equals(form.getPassword())) throw new UserException("Password error!"); if(!user.isState()) throw new UserException("Not activated yet!"); return user; }}2.5 UserDao
/** * User persistence layer*/public class UserDao { private QueryRunner qr = new TxQueryRunner(); /** * Query by username* @param username * @return */ public User findByUsername(String username) { try { String sql = "select * from tb_user where username=?"; return qr.query(sql, new BeanHandler<User>(User.class), username); } catch(SQLException e) { throw new RuntimeException(e); } } /** * Query by email* @param email * @return */ public User findByEmail(String email) { try { String sql = "select * from tb_user where email=?"; return qr.query(sql, new BeanHandler<User>(User.class), email); } catch(SQLException e) { throw new RuntimeException(e); } } /** * Insert User * @param user */ public void add(User user) { try { String sql = "insert into tb_user values(?,?,?,?,?,?)"; Object[] params = {user.getUid(), user.getUsername(), user.getPassword(), user.getEmail(), user.getCode(), user.isState()}; qr.update(sql, params); } catch(SQLException e) { throw new RuntimeException(e); } } /** * Query by activation code* @param code * @return */ public User findByCode(String code) { try { String sql = "select * from tb_user where code=?"; return qr.query(sql, new BeanHandler<User>(User.class), code); } catch(SQLException e) { throw new RuntimeException(e); } } /** * Modify the specified state of the specified user* @param uid * @param state */ public void updateState(String uid, boolean state) { try { String sql = "update tb_user set state=? where uid=?"; qr.update(sql, state, uid); } catch(SQLException e) { throw new RuntimeException(e); } }}3. User activation
Process: User's email -> UserServlet#active() -> msg.jsp
4.
User login
Process: /jsps/user/login.jsp -> UserServlet#login() -> index.jsp
5.
User exit
Process: top.jsp -> UserServlet#quit() -> login.jsp
quit(): Destroy the session!
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.