天天看點

圖書商城:使用者子產品使用者子產品

圖書商城:使用者子產品使用者子產品

使用者子產品

1、使用者子產品的相關類建立

  • domain:User
  • dao:UserDao
  • service:UserDao
  • web.servlet:UserServlet

2、使用者注冊

2.1 注冊流程

/jsps/user/regist.jsp -> UserServlet#regist() -> msg.jsp

2.2 注冊頁面

<%@ 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>注冊</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" target="_blank" rel="external nofollow" >
    -->

  </head>

  <body>
  <h1>注冊</h1>
  <%--
   顯示errors --> 字段錯誤
   顯示異常錯誤
   回顯
   --%>
<p style="color: red; font-weight: 900">${msg }</p>
<form action="<c:url value='/UserServlet'/>" method="post">
    <input type="hidden" name="method" value="regist"/>
    使用者名:<input type="text" name="username" value="${form.username }"/>
    <span style="color: red; font-weight: 900">${errors.username }</span>
    <br/>
    密 碼:<input type="password" name="password" value="${form.password }"/>
    <span style="color: red; font-weight: 900">${errors.password }</span>
    <br/>
    郵 箱:<input type="text" name="email" value="${form.email }"/>
    <span style="color: red; font-weight: 900">${errors.email }</span>
    <br/>
    <input type="submit" value="注冊"/>
</form>
  </body>
</html>
           

2.3 UserServlet

User

/**
 * User的領域對象
 */
public class User {
    /*
     * 對應資料庫表
     */
    private String uid;// 主鍵
    private String username;// 使用者名
    private String password;// 密碼
    private String email;// 郵箱
    private String code;// 激活碼
    private boolean state;// 狀态(已激活和未激活)
           

BaseServlet

public class BaseServlet extends HttpServlet {
    /*
     * 它會根據請求中的method,來決定調用本類的哪個方法
     */
    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        res.setContentType("text/html;charset=utf-8");
        try {
            // 例如:http://localhost:8080/demo1/xxx?m=add
            String method = req.getParameter("method");// 它是一個方法名稱
            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表述層
 */
public class UserServlet extends BaseServlet {
    private UserService userService = new UserService();

    /**
     * 退出功能
     * @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. 封裝表單資料到form中
         * 2. 輸入校驗(不寫了)
         * 3. 調用service完成激活
         *   > 儲存錯誤資訊、form到request,轉發到login.jsp
         * 4. 儲存使用者資訊到session中,然後重定向到index.jsp
         */
        User form = CommonUtils.toBean(request.getParameterMap(), User.class);
        try {
            User user = userService.login(form);
            request.getSession().setAttribute("session_user", user);
            /*
             * 給使用者添加一個購物車,即向session中儲存一Cart對象
             */
            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";
        }
    }

    /**
     * 激活功能
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String active(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
         * 1. 擷取參數激活碼
         * 2. 調用service方法完成激活
         *   > 儲存異常資訊到request域,轉發到msg.jsp
         * 3. 儲存成功資訊到request域,轉發到msg.jsp
         */
        String code = request.getParameter("code");
        try {
            userService.active(code);
            request.setAttribute("msg", "恭喜,您激活成功了!請馬上登入!");
        } catch (UserException e) {
            request.setAttribute("msg", e.getMessage());
        }
        return "f:/jsps/msg.jsp";
    }

    /**
     * 注冊功能
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String regist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
         * 1. 封裝表單資料到form對象中
         * 2. 補全:uid、code
         * 3. 輸入校驗
         *   > 儲存錯誤資訊、form到request域,轉發到regist.jsp
         * 4. 調用service方法完成注冊
         *   > 儲存錯誤資訊、form到request域,轉發到regist.jsp
         * 5. 發郵件
         * 6. 儲存成功資訊轉發到msg.jsp
         */
        // 封裝表單資料
        User form = CommonUtils.toBean(request.getParameterMap(), User.class);
        // 補全
        form.setUid(CommonUtils.uuid());
        form.setCode(CommonUtils.uuid() + CommonUtils.uuid());
        /*
         * 輸入校驗
         * 1. 建立一個Map,用來封裝錯誤資訊,其中key為表單字段名稱,值為錯誤資訊
         */
        Map<String,String> errors = new HashMap<String,String>();
        /*
         * 2. 擷取form中的username、password、email進行校驗
         */
        String username = form.getUsername();
        if(username == null || username.trim().isEmpty()) {
            errors.put("username", "使用者名不能為空!");
        } else if(username.length() <  || username.length() > ) {
            errors.put("username", "使用者名長度必須在3~10之間!");
        }

        String password = form.getPassword();
        if(password == null || password.trim().isEmpty()) {
            errors.put("password", "密碼不能為空!");
        } else if(password.length() <  || password.length() > ) {
            errors.put("password", "密碼長度必須在3~10之間!");
        }

        String email = form.getEmail();
        if(email == null || email.trim().isEmpty()) {
            errors.put("email", "Email不能為空!");
        } else if(!email.matches("\\[email protected]\\w+\\.\\w+")) {
            errors.put("email", "Email格式錯誤!");
        }
        /*
         * 3. 判斷是否存在錯誤資訊
         */
        if(errors.size() > ) {
            // 1. 儲存錯誤資訊
            // 2. 儲存表單資料
            // 3. 轉發到regist.jsp
            request.setAttribute("errors", errors);
            request.setAttribute("form", form);
            return "f:/jsps/user/regist.jsp";
        }

        /*
         * 調用service的regist()方法
         */
        try {
            userService.regist(form);
        } catch (UserException e) {
            /*
             * 1. 儲存異常資訊
             * 2. 儲存form
             * 3. 轉發到regist.jsp
             */
            request.setAttribute("msg", e.getMessage());
            request.setAttribute("form", form);
            return "f:/jsps/user/regist.jsp";
        }

        /*
         * 發郵件
         * 準備配置檔案!
         */
        // 擷取配置檔案内容
        Properties props = new Properties();
        props.load(this.getClass().getClassLoader()
                .getResourceAsStream("email_template.properties"));
        String host = props.getProperty("host");//擷取伺服器主機
        String uname = props.getProperty("uname");//擷取使用者名
        String pwd = props.getProperty("pwd");//擷取密碼
        String from = props.getProperty("from");//擷取發件人
        String to = form.getEmail();//擷取收件人
        String subject = props.getProperty("subject");//擷取主題
        String content = props.getProperty("content");//擷取郵件内容
        content = MessageFormat.format(content, form.getCode());//替換{0}

        Session session = MailUtils.createSession(host, uname, pwd);//得到session
        Mail mail = new Mail(from, to, subject, content);//建立郵件對象
        try {
            MailUtils.send(session, mail);//發郵件!
        } catch (MessagingException e) {
        }


        /*
         * 1. 儲存成功資訊
         * 2. 轉發到msg.jsp
         */
        request.setAttribute("msg", "恭喜,注冊成功!請馬上到郵箱激活");
        return "f:/jsps/msg.jsp";
    }
}
           

2.4 UserService

/**
 * User業務層
 */
public class UserService {
    private UserDao userDao = new UserDao();

    /**
     * 注冊功能
     * @param form
     */
    public void regist(User form) throws UserException{

        // 校驗使用者名
        User user = userDao.findByUsername(form.getUsername());
        if(user != null) throw new UserException("使用者名已被注冊!");

        // 校驗email
        user = userDao.findByEmail(form.getEmail());
        if(user != null) throw new UserException("Email已被注冊!");

        // 插入使用者到資料庫
        userDao.add(form);
    }

    /**
     * 激活功能
     * @throws UserException 
     */
    public void active(String code) throws UserException {
        /*
         * 1. 使用code查詢資料庫,得到user
         */
        User user = userDao.findByCode(code);
        /*
         * 2. 如果user不存在,說明激活碼錯誤
         */
        if(user == null) throw new UserException("激活碼無效!");
        /*
         * 3. 校驗使用者的狀态是否為未激活狀态,如果已激活,說明是二次激活,抛出異常
         */
        if(user.isState()) throw new UserException("您已經激活過了,不要再激活了,除非你想死!");

        /*
         * 4. 修改使用者的狀态
         */
        userDao.updateState(user.getUid(), true);
    }

    /**
     * 登入功能
     * @param form
     * @return
     * @throws UserException 
     */
    public User login(User form) throws UserException {
        /*
         * 1. 使用username查詢,得到User
         * 2. 如果user為null,抛出異常(使用者名不存在)
         * 3. 比較form和user的密碼,若不同,抛出異常(密碼錯誤)
         * 4. 檢視使用者的狀态,若為false,抛出異常(尚未激活)
         * 5. 傳回user
         */
        User user = userDao.findByUsername(form.getUsername());
        if(user == null) throw new UserException("使用者名不存在!");
        if(!user.getPassword().equals(form.getPassword()))
            throw new UserException("密碼錯誤!");
        if(!user.isState()) throw new UserException("尚未激活!");

        return user;
    }
}
           

2.5 UserDao

圖書商城:使用者子產品使用者子產品
/**
 * User持久層
 */
public class UserDao {
    private QueryRunner qr = new TxQueryRunner();

    /**
     * 按使用者名查詢
     * @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查詢
     * @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);
        }
    }

    /**
     * 插入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);
        }
    }

    /**
     * 按激活碼查詢
     * @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);
        }
    }

    /**
     * 修改指定使用者的指定狀态
     * @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、使用者激活

流程:使用者的郵件中 -> UserServlet#active() -> msg.jsp

圖書商城:使用者子產品使用者子產品

4、使用者登入

流程:/jsps/user/login.jsp -> UserServlet#login() -> index.jsp

圖書商城:使用者子產品使用者子產品

5、使用者退出

流程:top.jsp -> UserServlet#quit() -> login.jsp

quit():把session銷毀!