Javaweb Book Mall Design user module (1) _java

Source: Internet
Author: User
Tags getmessage uuid

This article mainly for everyone to analyze the Book Mall user module, the specific contents are as follows

1, the user module related class creation

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

2.3 Userservlet

User

/**
 * User domain object/
 public
class User {/
 *
  * Corresponding database table * *
 private String uid;//primary key
 private String username;//user name
 private string password;//password
 private string email;//mailbox
 private string code;//activation code C12/>private boolean state;//state (activated and inactive)

Baseservlet

public class Baseservlet extends HttpServlet {
  * * * It will decide which method to call this class, based on the methods 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 ("methods");//It is a way name
   Class 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 Presentation 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. Input checksum (NO) * 3. Invoke service completes activation * > Save error message, form to request, forward to login.jsp * 4. Save with
  User information into session, 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);
   * * To 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 ioexceptio n */Public String Active (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcep tion {* * 1. Get parameter Activation code * 2. Invoke the service method to complete activation * > Save exception information to request field and forward to msg.jsp * 3. Save Success information to request field, forward to Msg.js
  p */String code = request.getparameter ("code");
   try {userservice.active (code); Request.setattribute ("msg", "Congratulations, your activation is successful!") Please login now!
  ");
  catch (Userexception e) {request.setattribute ("msg", E.getmessage ());
 Return to "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 to form Object * 2. Complement: UID, code * 3. Input CHECKSUM * > Save error message , form to request field, forwarded to REGIST.JSP * 4. Call service method completes registration * > Save error message, form to request field, forward to regist.jsp * 5. Send mail * 6.
  Save success message forward to msg.jsp//Encapsulate form data User form = Commonutils.tobean (Request.getparametermap (), user.class);
  Complement full Form.setuid (Commonutils.uuid ());
  Form.setcode (Commonutils.uuid () + commonutils.uuid ()); * * Input CHECKSUM * 1.
  Create a MAP that encapsulates the error message, where 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, email to verify the form */String username = Form.getusername (); if (username = null | | Username.trim (). IsEmpty ()) {Errors.put ("username", "user name cannot be empty!")
  "); else if (Username.length () < 3 | | username.length () > Ten) {errors.put ("username", "user name length must be between 3~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 () > Ten) {errors.put ("password", "password length 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 is wrong!")
  "); } * * 3. Determine if there is an error message */if (errors.size () > 0) {//1. Save error message//2. Save form data//3. Forward to regist.jsp Request.setattribu
   Te ("Errors", errors);
   Request.setattribute ("form", form);
  return "f:/jsps/user/regist.jsp";
  * * * the Regist () method for invoking the service is * * */try {userservice.regist (form); catch (Userexception e) {/* 1. Save exception Information * 2. Save form * 3. Forward to regist.jsp * * Request.setattribute ("M
   SG ", E.getmessage ());
   Request.setattribute ("form", form);
  return "f:/jsps/user/regist.jsp";
   * * * Send mail * prepare configuration file!
  //Get 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 user name string pwd = Props . GetProperty ("pwd");/get password string from = Props.getproperty (' from ');//Get sender string to = Form.getemail ();//Get Recipient Strin G subject = Props.getproperty ("subject"); Get the subject String content = Props.getproperty ("content")//Get message content = Messa Geformat.format (content, Form.getcode ()),//replace {0} session session = Mailutils.createsession (host, uname, PWD);
  Get session mail = new mail (from, to, subject, content);//Create a Mail object try {mailutils.send (session, mail);/e-mail! catch (Messagingexception e) {} * * 1. Save Success Information * 2. Forward to msg.jsp/Request.setattribute ("MSG", "Congratulations, registration success!")
  Please immediately to the mailbox activation ");
 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 regist (user form) throws userexception{//verify username user = Userdao.f
  Indbyusername (Form.getusername ()); if (user!= null) throw new Userexception ("username is already registered!")

  ");
  Verify Email user = Userdao.findbyemail (Form.getemail ()); if (user!= null) throw new Userexception ("email has been registered!")

  ");
 Insert user to database Userdao.add (form); /** * Activation function * @throws userexception/public void Active (String code) throws userexception {* * * 1. Using CO
  De query database, get user * * user = Userdao.findbycode (code); * * 2. If user does not exist, the activation code error */if (user = null) throw new userexception ("Invalid Activation Code!")
  "); * * 3. Verify that the user's State is inactive and, if activated, two activation, throws an exception/if (User.isstate ()) throw new Userexception ("You have activated, do not activate, 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 query to get user * 2. If user is null, throw an exception ( Name does not exist) * 3. Compare form and user passwords, if different, throw an exception (password error) * 4. View the user's status, false, throw an exception (not activated) * 5.
  Returns user */user user = Userdao.findbyusername (form.getusername ()); if (user = null) throw new Userexception ("username does not exist!")
  "); if (!user.getpassword (). Equals (Form.getpassword ())) throw new Userexception ("Bad password!
  "); if (!user.isstate ()) throw new Userexception ("Not yet activated!")

  ");
 return user;

 }
}

2.5 Userdao

/** * User Persistence Layer */public class Userdao {private Queryrunner QR = new Txqueryrunner ();  /** * by user name * @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);  /** * Email Inquiry * @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 valu
   ES (?,?,?,?,?,?) "; 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); /** * by Activation Code query * @param code * @return/Public User Findbycode (string code) {try {String sql = ' sel
   ECT * from Tb_user where code=? ";
  return qr.query (SQL, New beanhandler<user> (User.class), code);
  catch (SQLException e) {throw new RuntimeException (e); }/** * Modifies the specified state of the specified user * @param uid * @param states/public void Updatestate (String uid, Boolean state) {TR y {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:-> userservlet#active ()-> in the user's message msg.jsp

4,

User Login

Process:/jsps/user/login.jsp-> userservlet#login ()-> index.jsp

5,

User exits

Process: top.jsp-> userservlet#quit ()-> login.jsp

Quit (): Destroy the session!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.