java Web中实现QQ邮箱验证以及验证码注册用户

来源:互联网 发布:编程单引号怎么打 编辑:程序博客网 时间:2024/05/01 22:26

实体类: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("1210411628@qq.com", "vtenvupfptwpiajj");
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("1210411628@qq.com")); // 设置发送者
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);
}
}

通过工具类实现发送邮件验证注册,点击链接激活用户后,可登陆。
原创粉丝点击