用户注册_发邮件,激活

servlet:

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() < 3 || username.length() > 10) {
            errors.put("username", "用户名长度必须在3~10之间!");
        }
        
        String password = form.getPassword();
        if(password == null || password.trim().isEmpty()) {
            errors.put("password", "密码不能为空!");
        } else if(password.length() < 3 || password.length() > 10) {
            errors.put("password", "密码长度必须在3~10之间!");
        }
        
        String email = form.getEmail();
        if(email == null || email.trim().isEmpty()) {
            errors.put("email", "Email不能为空!");
        } else if(!email.matches("\w+@\w+\.\w+")) {
            errors.put("email", "Email格式错误!");
        }
        /*
         * 3. 判断是否存在错误信息
         */
        if(errors.size() > 0) {
            // 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";
    }

service:

 1 /**
 2      * 注册功能
 3      * @param form
 4      */
 5     public void regist(User form) throws UserException{
 6         
 7         // 校验用户名
 8         User user = userDao.findByUsername(form.getUsername());
 9         if(user != null) throw new UserException("用户名已被注册!");
10         
11         // 校验email
12         user = userDao.findByEmail(form.getEmail());
13         if(user != null) throw new UserException("Email已被注册!");
14         
15         // 插入用户到数据库
16         userDao.add(form);
17     }
18     
19     /**
20      * 激活功能
21      * @throws UserException 
22      */
23     public void active(String code) throws UserException {
24         /*
25          * 1. 使用code查询数据库,得到user
26          */
27         User user = userDao.findByCode(code);
28         /*
29          * 2. 如果user不存在,说明激活码错误
30          */
31         if(user == null) throw new UserException("激活码无效!");
32         /*
33          * 3. 校验用户的状态是否为未激活状态,如果已激活,说明是二次激活,抛出异常
34          */
35         if(user.isState()) throw new UserException("您已经激活过了,不要再激活了,除非你想死!");
36         
37         /*
38          * 4. 修改用户的状态
39          */
40         userDao.updateState(user.getUid(), true);
41     }

dao:

/**
     * 按用户名查询
     * @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);
        }
    }
    
    /**
     * 按用户名查询
     * @param username
     * @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);
        }
    }
}

jsp:

  <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 ="${from.passwrod}"/>    
<span style="color: red; font-weight: 900">${errors.password }</span><br />
    邮 箱:<input type="text" name="email" value="${from.email}"/>
    <span style="color: red; font-weight: 900">${errors.email }</span><br />
    <input type="submit" value="注册"/>
</form>
原文地址:https://www.cnblogs.com/xiaoxiao5ya/p/4935869.html