JavaEE账号注册模拟网站邮箱激活

本项目是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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 分享关于JAVA 中使用Preferences读写注册表时要注意的地方

    要注意的只有一个地方,那就是键名或者项名不要包含大写字母,否则读不到数据. 代码是这样的: 复制代码 代码如下: Preferences preferences = Preferences.systemRoot();String strRegTime = preferences.get("regTime", ""); 注册表中是这样的 不论怎么改都读不到regTime的值.后来想到现在代码中把值写进去看看是什么样的,代码如下 复制代码 代码如下: Preferenc

  • java用户管理注册功能 含前后台代码

    本文实例为大家分享了java用户注册功能,供大家参考,具体内容如下 主页面: 浏览器显示: 代码实现: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <title>用户信息管理</title> </head> <body> 用户注册:<br

  • Java注册邮箱激活验证实现代码

    最近从项目分离出来的注册邮箱激活功能,整理一下,方便下次使用 RegisterValidateService.java 复制代码 代码如下: package com.app.service.impl; import java.text.ParseException;import java.util.Date; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stere

  • 注册验证java代码[针对上篇文章]

    http://www.jb51.net/article/19801.htm 复制代码 代码如下: <%@ page contentType="text/html; charset=gb2312" language="java"%> <%@ page import="java.sql.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional/

  • java实现简单注册选择所在城市

    本文实例为大家分享了java实现简单注册选择所在城市的全部代码,供大家参考,具体内容如下 1.activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.androi

  • Servlet+JavaBean+JSP打造Java Web注册与登录功能

    采用Java Web所实现的MVC结构图如下,其中控制器部分采用Servlet来实现,模型部分采用JavaBean来实现,而大部分的视图采用Jsp页面来实现. 思想基础 JSP+JavaBean两层结构工作原理应该是比较熟悉的,也比较好理解. 但是有一点必须要清楚就是用户通过浏览器来发送网页的请求,此请求到达服务器后在服务器端查找对应的网页,如果是首次请求(第二次就不用解释执行了),对于JSP来说要生成Servlet,然后通过Servlet引擎来执行 Servlet,把调用JavaBean的结果

  • JAVA简单链接Oracle数据库 注册和登陆功能的实现代码

    复制代码 代码如下: //User 用户的基本信息,也是USERINFO表中的3个列package 登陆判断; public class User { private String name;  private String loginname;  private String loginpsw;  public String getName() {   return name;  }  public void setName(String name) {   this.name = name;

  • JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式)

    下面通过通过图文并茂的方式给大家介绍JavaWeb实现用户登录注册功能实例代码,一起看看吧. 一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp负责数据显示,javabean负责封装数据. Servlet+JSP+JavaBean模式程序各个模块之间层次清晰,web开发推荐采用此种模式. 这里以一个最常用的用户登录注册程序来讲解Servlet+JS

  • 深入java事件注册的应用分析

    对上次的三个问题的个人理解: 1) 程序首先是从main函数开始执行的,假设main 函数不是 static ,就要先实例化这个类,然后调用 main 方法,这似乎是不现实的. 其次 用 static 修饰的 main 方法是存储在静态的存贮区当中的,也就是说在创建一个类之后,main 函数就已经存在了,去掉 static 修饰之后,编译可以通过,但是不能执行.2)查 API之后才发现BufferedRead 对象的 readLine()方读到的数据是,读到有换行的地方为一行,直接用 readL

  • JAVA实现简单系统登陆注册模块

    前期准备 首先要先明确有个大体的思路,要实现什么样的功能,了解完成整个模块要运用到哪些方面的知识,以及从做的过程中去发现自己的不足.技术方面的进步大都都需要从实践中出来的. 功能:用户注册功能+系统登录功能+生成验证码 知识:窗体设计.数据库设计.JavaBean封装属性.JDBC实现对数据库的连接.验证码(包括彩色验证码)生成技术,还有就些比如像使用正则表达式校验用户注册信息.随机获得字符串.对文本可用字符数的控制等 设计的模块预览图: 彩色验证码预览图: 所用数据库:MySQL 数据库设计

随机推荐