JavaEE账号注册模拟网站邮箱激活
时间:2023-01-20 09:34:33|栏目:JAVA代码|点击: 次
本项目是javaWeb和email结合的项目,模拟网站必须要激活邮箱账号才可以使用,
创建数据库
create table user( id varchar(32) primary key, name varchar(30), pwd varchar(20), email varchar(20), active char(1), acode varchar(32) )
User.java值对象
package cn.hncu.reg.domain; import javax.persistence.Table; public class User { private String id; private String name; private String pwd; private String acode; private String active; private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getAcode() { return acode; } public void setAcode(String acode) { this.acode = acode; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
C3p0Pool.java
package cn.hncu.pubs; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3p0Pool { private static DataSource ds=new ComboPooledDataSource();; private static ThreadLocal<Connection> tl=new ThreadLocal<Connection>(); public static Connection getCon() throws SQLException { Connection con = (Connection)tl.get(); if (con == null) { con = ds.getConnection(); tl.set(con); } return con; } public static DataSource getPool() { return ds; } public static ThreadLocal<Connection> getTl() { return tl; } }
C3p0-config.xml
<c3p0-config> <!-- 默认配置,如果没有指定则使用这个配置 --> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> <![CDATA[jdbc:mysql://127.0.0.1:3306/sstud?useUnicode=true&characterEncoding=UTF-8]]> </property> <property name="user">root</property> <property name="password">1234</property> <!-- 初始化池大小 --> <property name="initialPoolSize">2</property> <!-- 最大空闲时间 --> <property name="maxIdleTime">30</property> <!-- 最多有多少个连接 --> <property name="maxPoolSize">10</property> <!-- 最少几个连接 --> <property name="minPoolSize">2</property> <!-- 每次最多可以执行多少个批处理语句 --> <property name="maxStatements">50</property> </default-config> <!-- 命名的配置 --> <named-config name="hncu"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/sstud</property> <property name="user">root</property> <property name="password">1234</property> <property name="acquireIncrement">5</property><!-- 如果池中数据连接不够时一次增长多少个 --> <property name="initialPoolSize">100</property> <property name="minPoolSize">50</property> <property name="maxPoolSize">1000</property> <property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property> <!-- he's important, but there's only one of him --> </named-config> </c3p0-config>
RegDAO.java
package cn.hncu.reg.dao; import cn.hncu.reg.domain.User; public interface RegDAO { public User reg(User user); public User active(String acode); }
RegDaoJdbc.java
package cn.hncu.reg.dao; import java.sql.SQLException; import java.util.UUID; import javax.sql.DataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import cn.hncu.pool.C3p0Pool; import cn.hncu.reg.domain.User; public class RegDaoJdbc implements RegDAO{ @Override public User reg(User user) { DataSource ds=C3p0Pool.getPool(); QueryRunner qr=new QueryRunner(ds); String sql="insert into user(id,name,pwd,email,active,acode) values(?,?,?,?,?,?)"; try { String id=UUID.randomUUID().toString().replaceAll("-", ""); String acode=UUID.randomUUID().toString().replaceAll("-", ""); qr.update(sql,id,user.getName(),user.getPwd(),user.getEmail(),"0",acode); user.setAcode(acode); user.setId(id); user.setActive("0"); } catch (SQLException e) { // e.printStackTrace(); System.out.println("注册失败"); return null; } return user; } @Override public User active(String acode) { DataSource ds=C3p0Pool.getPool(); QueryRunner qr=new QueryRunner(ds); String sql="select * from user where acode=?"; User user=null; try { user=qr.query(sql, new BeanHandler(User.class),acode); if(user!=null){ sql="update user set active='1' ,acode=''where acode=?"; qr.update(sql,acode); return user; } } catch (SQLException e) { user=null; e.printStackTrace(); } return null; } }
IRegService.java
package cn.hncu.reg.service; import cn.hncu.reg.domain.User; public interface IRegService { public User reg(User user); public User active(String acode); }
RegService.java
package cn.hncu.reg.service; import cn.hncu.reg.dao.RegDAO; import cn.hncu.reg.dao.RegDaoJdbc; import cn.hncu.reg.domain.User; public class RegService implements IRegService { private RegDAO dao=new RegDaoJdbc(); @Override public User reg(User user) { return dao.reg(user); } @Override public User active(String acode) { return dao.active(acode); } }
RegServlet.java
package cn.hncu.reg.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.reg.domain.User; import cn.hncu.reg.sendMail.SendEMailThread; import cn.hncu.reg.service.IRegService; import cn.hncu.reg.service.RegService; public class RegServlet extends HttpServlet { private IRegService service=new RegService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("请按要求填写"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String name=request.getParameter("name"); String pwd=request.getParameter("pwd"); String email=request.getParameter("email"); User user=new User(); user.setName(name); user.setPwd(pwd); user.setEmail(email); user=service.reg(user); if (user!=null) { out.print("注册成功,请到邮箱验证"); new SendEMailThread(user.getAcode()).start(); }else{ out.print("注册失败"); } } }
SendEMailThread.java
package cn.hncu.reg.sendMail; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; public class SendEMailThread extends Thread { private String acode; private Logger log=Logger.getLogger(SendEMailThread.class); public SendEMailThread(String acode) { this.acode = acode; } @Override public void run() { Properties p=new Properties(); p.setProperty("mail.host", "smtp.sina.com"); p.setProperty("mail.smtp.auth", "true"); Session session=Session.getDefaultInstance(p, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { PasswordAuthentication pa=new PasswordAuthentication("hncujava", "1234567"); return pa; } }); session.setDebug(true); MimeMessage msg=new MimeMessage(session); try { msg.setFrom( new InternetAddress("hncujava@sina.com") ); msg.setRecipient(RecipientType.TO, new InternetAddress("747205398@qq.com")); msg.setSubject("激活hncu账号"); StringBuilder sb=new StringBuilder(); sb.append("请激活邮箱:<a href='http://127.0.0.1:8080/mailWeb/ActiveServlet"); sb.append("?acode="+acode+" '>点击激活</a>"); sb.append("<br/>如果激活未成功,请复制下面地址到浏览器地址栏进行手动激活:"); sb.append("http://www.hncu.cn/mailWeb/ActiveServlet?acode="+acode); msg.setContent(sb.toString(),"text/html;charset=utf-8"); Transport.send(msg); log.info("邮件发送成功"); } catch (AddressException e) { log.error("邮箱地址错误,邮件发送失败"); e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); log.error("邮箱信息格式错误,邮件发送失败"); } } }
ActiveServlet.java
package cn.hncu.reg.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.reg.domain.User; import cn.hncu.reg.service.IRegService; import cn.hncu.reg.service.RegService; public class ActiveServlet extends HttpServlet { private IRegService service=new RegService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String acode=request.getParameter("acode"); User user=service.active(acode); request.setAttribute("user", user); System.out.println("user:"+user); request.getRequestDispatcher("/jsps/result.jsp").forward(request, response); } }
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>邮箱登录</title> <script type="text/javascript"> function reg(){ document.forms[0].action='<c:url value="/jsps/reg.jsp"/>'; document.forms[0].submit(); } function login(){ document.forms[0].action='<c:url value="/LoginServlet"/>'; document.forms[0].submit(); } </script> </head> <body> <c:if test="${!empty error }"> 登录失败 <c:remove var="error" scope="session"/> </c:if> <c:if test="${empty sessionScope.user }" var="boo"> <h3>用户注册</h3> <form action="" method="post" > 姓名:<input type="text" name="name" value="wang"/><br/> 密码:<input type="text" name="pwd" value="1234"/><br/> <input type="button" value="登录" onclick="login();"/> <input type="button" value="注册" onclick="reg();"/><br/> </form> </c:if> <c:if test="${!boo }"> 欢迎回来,${ sessionScope.user.name} </c:if> </body> </html>
reg.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>邮箱注册系统</title> <script type="text/javascript"> function reg(){ document.forms[0].action='<c:url value="/RegServlet"/>'; document.forms[0].submit(); } function login(){ document.forms[0].action='<c:url value="/LoginServlet"/>'; document.forms[0].submit(); } </script> </head> <body> <c:if test="${empty sessionScope.user }" var=" boo"> <h3>用户注册</h3> <form action="" method="post" > 姓名:<input type="text" name="name" value="wang"/><br/> 密码:<input type="text" name="pwd" value="1234"/><br/> 邮箱:<input type="text" name="email" value="747205398@qq.com"/> <br/> <input type="button" value="注册" onclick="reg();"/><br/> </form> </c:if> </body> </html>
result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript"> var tm; var time=5; function start(){ div1.innerHTML="将在"+time+"秒跳转"; time--; if(time<=1){ window.clearInterval(tm); window.location.href="<c:url value='/index.jsp'/>"; } } onload=function(){ tm=window.setInterval(start, 1000); }; </script> </head> <body> <c:if test="${!empty requestScope.user }" var=" boo"> 恭喜注册成功!请登录 <a href='<c:url value="/index.jsp" />'>登录</a><br/><br/> <div id ="div1"> </div> </c:if> <c:if test="${boo}"> 注册失败,请重新激活 </c:if> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <filter> <filter-name>charset</filter-name> <filter-class>cn.hncu.filter.CharacterFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>charset</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>RegServlet</servlet-name> <servlet-class>cn.hncu.reg.servlet.RegServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>ActiveServlet</servlet-name> <servlet-class>cn.hncu.reg.servlet.ActiveServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>cn.hncu.login.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegServlet</servlet-name> <url-pattern>/RegServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ActiveServlet</servlet-name> <url-pattern>/ActiveServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
需要的jar包
c3p0-0.9.1.2.jar
commons-dbutils-1.4.jar
java-mail-1.4.4.jar
mysql-connector-java-5.1.34-bin.jar
myConUtil.jar
栏 目:JAVA代码
下一篇:详解spring cloud如何使用spring-test进行单元测试
本文标题:JavaEE账号注册模拟网站邮箱激活
本文地址:http://www.codeinn.net/misctech/224065.html