1. 程式人生 > >java Web中實現QQ郵箱驗證以及驗證碼註冊使用者

java Web中實現QQ郵箱驗證以及驗證碼註冊使用者

實體類:User.java

package com.yinhe.bean;
import java.util.Date;

public class User {
private String uid;
private String username;
private String password;
private String name;
private String email;
private String telephone;
private Date birthday = new Date();
private String sex;
private int state;//是否啟用
private String code;//啟用碼
public String getUid() {
return uid;
}
public void setUid(String 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 getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}

UserDao.java

package com.yinhe.dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.yinhe.bean.User;
import com.yinhe.utils.DataSourceUtils;


public class UserDao {
// 儲存user
public int addUser(User user) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)";
int update = qr.update(sql, user.getUid(), user.getUsername(),
user.getPassword(), user.getName(), user.getEmail(),
user.getTelephone(), user.getBirthday(), user.getSex(),
user.getState(), user.getCode());
return update;
}
//修改狀態為1
public int updateState(String uid) throws SQLException{
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "update user set state = 1 where uid=?";
int update = qr.update(sql,uid);
return update;
}
//根據使用者 名查詢使用者
public int findUserByUsername(String username) throws SQLException{
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select count(*) from user where username = ?";
int count = ((Long)qr.query(sql, new ScalarHandler(), username)).intValue();
return count;
}
}

UserService.java

package com.yinhe.service;
import java.sql.SQLException;
import com.yinhe.bean.User;
import com.yinhe.dao.UserDao;
import com.yinhe.utils.CommonsUtils;


public class UserService {
private UserDao ud = new UserDao();
// 註冊
public boolean addUser(User user){
//給user賦值uid
user.setUid(CommonsUtils.getUUID());
//給user賦code
user.setCode(user.getUid());
try {
return ud.addUser(user) > 0 ? true : false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//修改狀態為1
public boolean updateState(String uid){
try {
return ud.updateState(uid)>0?true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//根據使用者 名查詢使用者
public boolean findUserByUsername(String username){
try {
return ud.findUserByUsername(username) > 0 ? false : true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}

Servlet層

package com.yinhe.web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import com.yinhe.bean.User;
import com.yinhe.service.UserService;
import com.yinhe.utils.MailUtils;


public class UserServlet extends BaseServlet {
private UserService us = new UserService();
public void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, IllegalAccessException, InvocationTargetException{
Map<String, String[]> properties = request.getParameterMap();
User user = new User();
// 自定義型別轉換器
ConvertUtils.register(new Converter() {
public Object convert(Class cla, Object value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(value.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}, Date.class);
// 封裝屬性
BeanUtils.populate(user, properties);
// 校驗驗證碼
if (request.getParameter("code").equals(request.getSession().getAttribute("sRand"))) {
boolean result = us.addUser(user);
//code與uid一致 方便驗證
String emailMsg = "恭喜您註冊成功,請點選下面的連線進行啟用賬戶"
+ "<a href='http://localhost:8080/ShopStore/user?method=validate&&activeCode="
+ user.getCode() + "'>"
+ "http://localhost:8080/ShopStore/login.jsp</a>";
if (result) {
try {
MailUtils.sendMail(user.getEmail(), emailMsg);
response.sendRedirect("/ShopStore/registerSuccess.jsp");
} catch (Exception e) {
// 傳送失敗
response.sendRedirect("/ShopStore/registerFail.jsp");
e.printStackTrace();
}
} else {
response.getWriter().println("<script>confirm('註冊失敗');location.href='/ShopStore/register.jsp';</script>");
}
}else{
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("<script>alert('succes哈哈哈');location.href='/ShopStore/register.jsp';</script>");
}
}
// 啟用
public void validate(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
IllegalAccessException, InvocationTargetException {
String activeCode = request.getParameter("activeCode");
// 啟用碼與uid一致
us.updateState(activeCode);
response.sendRedirect("/ShopStore/login.jsp");
}
//註冊校驗使用者名稱是否存在
public void checkUser(HttpServletRequest request,
HttpServletResponse response) throws IOException{
boolean result = us.findUserByUsername(request.getParameter("username"));
//{"username":"aaaa","status:200","":{},"":[]}
String jsonString = "{'result':"+result+"}";
response.getWriter().println(jsonString);
}
}

工具類:MailUtils.java

package com.yinhe.utils;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
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 javax.mail.internet.MimeMessage.RecipientType;


public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1.建立一個程式與郵件伺服器會話物件 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.auth", "true");// 指定驗證為true
props.put("mail.smtp.ssl.enable", "true");
// 建立驗證器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "vtenvupfptwpiajj");
}
};
Session session = Session.getInstance(props, auth);
// 2.建立一個Message,它相當於是郵件內容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]")); // 設定傳送者
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設定傳送方式與接收者
message.setSubject("使用者啟用");
// message.setText("這是一封啟用郵件,請<a href='#'>點選</a>");
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.建立 Transport用於將郵件傳送
Transport.send(message);
}
}

通過工具類實現傳送郵件驗證註冊,點選連結啟用使用者後,可登陸。