1. 程式人生 > >jsp登入並實現郵箱啟用功能

jsp登入並實現郵箱啟用功能

1.新建一個Dynamic Web Project專案,裡面加入要用到的jar包,整體的框架如圖所示:


2.新建一個數據庫,裡面新建一張表,表結構如圖所示:


3.用易郵郵件伺服器新建幾個賬號,整體框架如圖所示:


4.用foxmail新建幾個郵箱,整體框架如下所示:


5.UserDao.java程式碼:

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程式碼:
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程式碼:
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程式碼:
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程式碼:
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程式碼:
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程式碼:
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程式碼:
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程式碼:
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("[email protected]", "root");
			}
		});
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress("[email protected]"));
		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程式碼:
package utils;

import java.util.UUID;

public class UUIDUtils {

	public static String getUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

}

15.c3p0-config.xml程式碼:
<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程式碼:
<?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程式碼:
<%@ 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程式碼:
<%@ 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的狀態,比較一下兩者的不同:







相關推薦

jsp登入實現郵箱啟用功能

1.新建一個Dynamic Web Project專案,裡面加入要用到的jar包,整體的框架如圖所示: 2.新建一個數據庫,裡面新建一張表,表結構如圖所示: 3.用易郵郵件伺服器新建幾個賬號,整體框架如圖所示: 4.用foxmail新建幾個郵箱,整體框架如下所示

JAVA實現郵箱註冊功能

前言 現在的網際網路專案中基本都實現了郵箱註冊的功能,但是該如何實現了,想必沒接觸過得人心裡應該沒有個具體的步驟 現在我們來看下是如何具體的實現一個郵箱註冊的功能。 第一步、先選用個郵箱作為例項 以QQ郵箱為例,開啟POP3/IMAP/SMTP/Exchange/CardDAV/Ca

django註冊賬號時完成郵箱啟用功能

目標:完成傳送郵件的任務,讓使用者完成啟用的步驟 需要模組: #傳送郵件 #from django.core.mail import send_mail #加密解密 #from itsdangerous import TimedJSONWebSignatureSerializer as

在react中 實現 base64的圖片轉換成formdata格式實現上傳功能

如果不想要服務端實現處理base64格式的圖片的轉換,那麼在瀏覽器端來實現,部分屬於虛擬碼,僅作為開發參考,請勿直接拷貝使用

element-ui+vue2.0 實現登入實現一週內記住密碼

1.檔案目錄 2.主頁index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="

第一個SSM前端專案(六):完善註冊後端處理設定郵箱啟用模式

一、註冊功能後端設計     二、根據設計可以看出我們需要redis來做啟用碼的儲存工作,因此需要在框架中繼承redis 1) 在linux伺服器中安裝redis(建議在伺服器中直接安裝,這樣正式執行的時候比較好操作),可以檢視此篇文章:騰訊雲CentOS 7.4 64

呼叫系統相機,實現連續拍照功能

private void intoPhotos() { File mediaStorageDir = new File(FileUtil.getPathRoot()+"/ietmDatas","customPicture"); if (!mediaStorag

使用VS2010呼叫QtDesigner設計的UI檔案,實現控制元件功能

一、利用Qt Designer設計UI。 參見《Linux視窗程式設計—Qt4精彩例項分析》 1、使用Qt Designer設計對話方塊的步驟: 2、Qt Designer5中表單模板。 3、建立窗體,在窗體放置控制元件(拖動控制元件到窗體介面); 4、佈局控制元件

javaWeb實現郵箱驗證功能(二)

上篇寫的實現基本上是一個工具類,並沒封裝成下圖這樣方式(梨視訊註冊介面),現在開始完善上篇的java郵箱啟用驗證功。 java郵箱驗證地址:https://blog.csdn.net/BlackPlus28/article/details/85044068 -----------------

ThinkPhp5實現郵箱傳送功能

首先要傳送檔案你就要有一個SMTP伺服器(簡單郵件傳輸協議)有來發送郵件。當然有傳送就有接收。 POP3和IMAP就是用來接收郵件的服務。 POP3:簡單的郵件訪問協議,單向的,本地對郵件的操作不會同步到郵件伺服器,用來從郵件伺服器取得郵件。 IMAP:是一種比

Java實現郵箱啟用賬戶例項

在網站註冊時一般都會要驗證註冊使用者身份的合法性,通常的做法是提供手機號驗證或者郵箱驗證。 手機驗證:填寫手機號碼,點擊發送驗證碼,接收後填寫驗證碼比對,無誤後註冊成功。 郵箱驗證:註冊時填寫郵箱賬號,點選註冊,網站郵箱會給該郵箱傳送一封啟用郵件,使用者點選後啟用該賬號。

實現郵箱驗證功能的程式碼

package com.maxtech.util; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MyEmailAutherti

執行緒的幾種建立方式實現賣票功能

本篇簡單的講下執行緒的幾種建立方式並相應的實現售票功能一、執行緒建立public class ThreadTest { public static void main(String[] args) throws InterruptedException, Executio

C#利用Zxing.net生成條形碼和二維碼實現列印的功能

    開篇:zxing.net是.net平臺下編解條形碼和二維碼的工具。 Step1:使用VS2010新建一個窗體程式專案: Step2:新增三個類:分別是BarCodeClass.cs、DocementBase.cs、imageDocument.cs。(下

jsp連線oracle資料庫實現簡單登入功能,來自網路,部分修改。(亞信聯創實習)

共三個頁面:login.jsp、loginconf.jsp、loginsucess.jsp 使用者首先開啟login.jsp輸入使用者名稱及密碼,此時login.jsp會將輸入的使用者名稱及密碼提交到loginconf.jsp loginconf.jsp通過初始化連線資料庫

【解決】php實現頁面登入註冊功能實現跳轉

目錄如下:   思路是不通過資料庫等操作實現頁面(頁面比較簡陋,請笑納) 關於register功能 html頁面必要的表單功能 在頭部寫上 寫上條件判斷 if ($_SERVER['REQUEST_METHOD'] === 'POST') { login();

利用JSP+JS+CSS+Servlet實現使用者登入,儲存使用者名稱密碼功能

private void rememberMe(String userName,String password,HttpServletResponse response){ Cookie cook

使用Flask實現郵箱驗證啟用和使用者管理功能

Flask實現的功能: 使用者註冊增加郵箱驗證啟用功能 增加使用者管理功能(登入和登出) 目錄結構: 使用者註冊增加郵箱驗證啟用功能 1.user模型更新: # 生成賬戶啟用的token def generate_a

jsp登入驗證碼功能實現

package com.coffee.action; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.Buffere

android 自己定義dialog實現失去焦點(背景透明)的功能

super 效果 andro 教程 his 布局 .com tle near 前言:因為在項目中須要用到更新顯示動畫的需求,所以想到了dialog,自己定義dialog不難。網上教程非常多,可是在實現dialog背景透明的需求時,遇到了一點問題。網上的一些方法在我的機器