项目准备的工具和jar包请自行下载
链接: https://pan.baidu.com/s/1wYOPwscRkUlwWmfcxe_Elg 提取码: yi7q 复制这段内容后打开百度网盘手机App,操作更方便哦
1.新建一个Dynamic Web Project项目,里面加入要用到的jar包,整体的框架如图所示:
2.新建一个数据库,里面新建一张表,表结构如图所示:
3.用易邮邮件服务器新建几个账号,整体框架如图所示:
4.用foxmail新建几个邮箱,整体框架如下所示:
5.UserDao.java代码:
[java] view plain copy print?
- package dao;
- import java.sql.SQLException;
- import domain.User;
- public interface UserDao {
- void regist(User user) throws SQLException;
- User findByCode(String code) throws SQLException;
- void update(User user) throws SQLException;
- }
6.UserDaoImpl.java代码:
[java] view plain copy print?
- package dao;
- import java.sql.SQLException;
- import org.apache.commons.dbutils.QueryRunner;
- import org.apache.commons.dbutils.handlers.BeanHandler;
- import utils.JdbcUtils;
- import domain.User;
- public class UserDaoImpl implements UserDao {
- @Override
- public void regist(User user) throws SQLException {
- QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
- String sql = "insert into user values (?,?,?,?,?,?,?)";
- Object[] params = { user.getUid(), user.getUsername(),
- user.getPassword(), user.getNickname(), user.getEmail(),
- user.getState(), user.getCode() };
- queryRunner.update(sql, params);
- }
- @Override
- public User findByCode(String code) throws SQLException {
- QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
- String sql = "select * from user where code = ?";
- User user = queryRunner.query(sql, new BeanHandler<User>(User.class),
- code);
- return user;
- }
- @Override
- public void update(User user) throws SQLException {
- QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
- String sql = "update user set username=?,password=?,nickname=?,email=?,state=?,code=? where uid=?";
- Object[] param = { user.getUsername(), user.getPassword(),
- user.getNickname(), user.getEmail(), user.getState(),
- user.getCode(), user.getUid() };
- queryRunner.update(sql, param);
- }
- }
7.User.java代码:
[java] view plain copy print?
- package domain;
- public class User {
- private Integer uid;
- private String username;
- private String password;
- private String nickname;
- private String email;
- private Integer state;
- private String code;
- public Integer getUid() {
- return uid;
- }
- public void setUid(Integer uid) {
- this.uid = uid;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getNickname() {
- return nickname;
- }
- public void setNickname(String nickname) {
- this.nickname = nickname;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public Integer getState() {
- return state;
- }
- public void setState(Integer state) {
- this.state = state;
- }
- public String getCode() {
- return code;
- }
- public void setCode(String code) {
- this.code = code;
- }
- }
8.UserService.java代码:
[java] view plain copy print?
- package service;
- import domain.User;
- public interface UserService {
- void regist(User user) throws Exception;
- User findByCode(String code) throws Exception;
- void update(User user) throws Exception;
- }
9.UserServiceImpl.java代码:
[java] view plain copy print?
- package service;
- import utils.MailUtils;
- import dao.UserDao;
- import dao.UserDaoImpl;
- import domain.User;
- public class UserServiceImpl implements UserService {
- @Override
- public void regist(User user) throws Exception {
- UserDao userDao = new UserDaoImpl();
- userDao.regist(user);
- MailUtils.sendMail(user.getEmail(), user.getCode());
- }
- @Override
- public User findByCode(String code) throws Exception {
- UserDao userDao=new UserDaoImpl();
- return userDao.findByCode(code);
- }
- @Override
- public void update(User user) throws Exception {
- UserDao userDao=new UserDaoImpl();
- userDao.update(user);
- }
- }
10.ActiveServlet.java代码:
[java] view plain copy print?
- package servlet;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import domain.User;
- import service.UserService;
- import service.UserServiceImpl;
- @WebServlet("/ActiveServlet")
- public class ActiveServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- doPost(request, response);
- }
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- try {
- String code = request.getParameter("code");
- UserService userService = new UserServiceImpl();
- User user = userService.findByCode(code);
- if (user != null) {
- user.setState(1);
- user.setCode(null);
- userService.update(user);
- request.setAttribute("msg", "您的已经激活成功!请去登录!");
- } else {
- request.setAttribute("msg", "您的激活码有误,请重新激活!");
- }
- request.getRequestDispatcher("/msg.jsp").forward(request, response);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException();
- }
- }
- }
11.RegistServlet.java代码:
[java] view plain copy print?
- package servlet;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import service.UserService;
- import service.UserServiceImpl;
- import utils.UUIDUtils;
- import domain.User;
- public class RegistServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- doPost(request, response);
- }
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- try {
- request.setCharacterEncoding("utf-8");
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- String nickname = request.getParameter("nickname");
- String email = request.getParameter("email");
- User user = new User();
- user.setUsername(username);
- user.setPassword(password);
- user.setNickname(nickname);
- user.setEmail(email);
- user.setState(0);
- String code = UUIDUtils.getUUID() + UUIDUtils.getUUID();
- user.setCode(code);
- UserService userService = new UserServiceImpl();
- userService.regist(user);
- request.setAttribute("msg", "您已经注册成功,请去邮箱激活!");
- request.getRequestDispatcher("/msg.jsp").forward(request, response);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException();
- }
- }
- }
12.JdbcUtils.java代码:
[java] view plain copy print?
- package utils;
- import java.sql.Connection;
- import java.sql.SQLException;
- import javax.sql.DataSource;
- import com.mchange.v2.c3p0.ComboPooledDataSource;
- public class JdbcUtils {
- private static DataSource ds = new ComboPooledDataSource();
- private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
- public static DataSource getDataSource() {
- return ds;
- }
- public static Connection getConnection() throws SQLException {
- Connection con = tl.get();
- if (con != null)
- return con;
- return ds.getConnection();
- }
- public static void beginTransaction() throws SQLException {
- Connection con = tl.get();
- if (con != null)
- throw new SQLException("已经开启了事务,不能重复开启!");
- con = ds.getConnection();
- con.setAutoCommit(false);
- tl.set(con);
- }
- public static void commitTransaction() throws SQLException {
- Connection con = tl.get();
- if (con == null)
- throw new SQLException("没有事务不能提交!");
- con.commit();
- con.close();
- con = null;
- tl.remove();
- }
- public static void rollbackTransaction() throws SQLException {
- Connection con = tl.get();
- if (con == null)
- throw new SQLException("没有事务不能回滚!");
- con.rollback();
- con.close();
- con = null;
- tl.remove();
- }
- public static void releaseConnection(Connection connection)
- throws SQLException {
- Connection con = tl.get();
- if (connection != con) {
- if (connection != null && !connection.isClosed()) {
- connection.close();
- }
- }
- }
- }
13.MailUtils.java代码:
[java] view plain copy print?
- package utils;
- import java.util.Properties;
- import javax.mail.Authenticator;
- import javax.mail.Message;
- import javax.mail.Transport;
- import javax.mail.Message.RecipientType;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- public class MailUtils {
- public static void sendMail(String to, String code) throws Exception {
- Properties properties = new Properties();
- Session session = Session.getInstance(properties, new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("service@store.com", "root");
- }
- });
- Message message = new MimeMessage(session);
- message.setFrom(new InternetAddress("service@store.com"));
- message.setRecipient(RecipientType.TO, new InternetAddress(to));
- message.setSubject("来自XX网站的激活邮件");
- message.setContent(
- "<h1>来自XX网站的激活邮件,点击</h1><h3><a href='http://localhost:8080/regist/ActiveServlet?code="
- + code
- + "'>http://localhost:8080/regist/ActiveServlet?code="
- + code + "</a></h3>", "text/html;charset=utf-8");
- Transport.send(message);
- }
- }
14.UUIDUtils.java代码:
[java] view plain copy print?
- package utils;
- import java.util.UUID;
- public class UUIDUtils {
- public static String getUUID() {
- return UUID.randomUUID().toString().replace("-", "");
- }
- }
15.c3p0-config.xml代码:
[html] view plain copy print?
- <c3p0-config>
- <default-config>
- <property name="jdbcUrl">jdbc:mysql://localhost:3306/regist_web?characterEncoding=utf-8</property>
- <property name="driverClass">com.mysql.jdbc.Driver</property>
- <property name="user">root</property>
- <property name="password">root</property>
- <property name="checkoutTimeout">30000</property>
- <property name="idleConnectionTestPeriod">30</property>
- <property name="initialPoolSize">10</property>
- <property name="maxIdleTime">30</property>
- <property name="maxPoolSize">100</property>
- <property name="minPoolSize">10</property>
- <property name="maxStatements">200</property>
- </default-config>
- </c3p0-config>
16.web.xml代码:
[html] view plain copy print?
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
- <display-name>regist</display-name>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>RegistServlet</servlet-name>
- <servlet-class>servlet.RegistServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>RegistServlet</servlet-name>
- <url-pattern>/RegistServlet</url-pattern>
- </servlet-mapping>
- </web-app>
17.msg.jsp代码:
[html] view plain copy print?
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <h1>${msg }</h1>
- </body>
- </html>
18.regist.jsp代码:
[html] view plain copy print?
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <h1>用户注册的界面</h1>
- <form action="RegistServlet" method="post">
- <table width="600" border="1">
- <tr>
- <td>用户名:</td>
- <td><input type="text" name="username"/></td>
- </tr>
- <tr>
- <td>密码:</td>
- <td><input type="password" name="password"/></td>
- </tr>
- <tr>
- <td>昵称:</td>
- <td><input type="text" name="nickname"/></td>
- </tr>
- <tr>
- <td>邮箱:</td>
- <td><input type="text" name="email"/></td>
- </tr>
- <tr>
- <td colspan="2"><input type="submit" value="注册"/></td>
- </tr>
- </table>
- </form>
- </body>
- </html>
19.在浏览器里面输入http://localhost:8080/regist/regist.jsp运行,输入user01和user02的信息,其中user01只是注册,不按照提示去邮件激活,而user02则根据提示去邮件激活,然后看看数据库里面的code和state的状态,比较一下两者的不同: