? ? ? ?
網(wǎng)站用戶注冊:
? ? ? ? 主要實(shí)現(xiàn)如下兩個(gè)功能:
1枪眉、用戶在網(wǎng)站上注冊完成后給用戶發(fā)一封郵件。
2贪绘、用戶通過郵件激活后才可以登錄炎咖。
思路:
首先需要一個(gè)思路:
? ? ? ? 用戶在前臺點(diǎn)擊注冊,向controller提交請求来农,把用戶提交過來的信息封裝成一個(gè)user(需要的信息有name,pwd,email這3個(gè)是用戶填寫的,我們幫用戶生成的是id和一個(gè)郵箱激活鏈接地址的唯一標(biāo)識碼acode鞋真,還要一個(gè)用來識別用戶是否已經(jīng)點(diǎn)擊鏈接的變量active)。 如果用戶點(diǎn)擊了鏈接后沃于,我們會將用戶的狀態(tài)修改為true【對應(yīng)的“”1”】涩咖,當(dāng)我們登入時(shí),會根據(jù)返會的actived狀態(tài)繁莹,來判斷用戶是否已經(jīng)激活了賬戶檩互,若未激活,則登錄不進(jìn)去咨演,否則闸昨,則可以;
? ? ? ? 并且不能使用該郵箱重復(fù)注冊用戶薄风,所以每次注冊用戶時(shí)饵较,都會先通過郵箱查詢該郵箱是否已經(jīng)注冊過了,沒有遭赂,則可以注冊循诉,否則不行。
? ? ? ? 用戶點(diǎn)了激活鏈接后撇他,再自動(dòng)跳轉(zhuǎn)到登錄頁面茄猫!
1:.POM.xml中導(dǎo)入javaxmail需要的依賴
2:controller類
package com.chinasofti.controller;
import com.chinasofti.pojo.User;
import com.chinasofti.service.UserService;
import com.chinasofti.util.EmailUtils;
import com.chinasofti.util.GenerateLinkUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;
@Controller
@RequestMapping("email")
public class UserController {
? ? @Autowired
? ? private UserService userService;
? ? @RequestMapping("toregist")
? ? public String toemail() {
? ? ? ? return "regist";
? ? }
@RequestMapping("login")
public? String login(){
? ? ? ? return "login";
}
? ? @RequestMapping("/regist")
? ? public void regist(User user, HttpSession httpSession, HttpServletResponse response) {
? ? ? ? user.setActivated(false);? //剛注冊默認(rèn)是沒有激活狀態(tài)
? ? ? ? user.setCodeUrl(UUID.randomUUID().toString());
? ? ? ? //注冊用戶
? ? ? ? User user1=userService.findUserByEmail(user.getEmail());
? ? ? ? if (user1==null) {
? ? ? ? ? ? userService.saveUser(user);
? ? ? ? } else {
? ? ? ? ? ? throw new RuntimeException("該郵箱已注冊");
? ? ? ? }
? ? ? ? //查看是否注冊成功,為實(shí)體類User的id賦值
? ? ? ? User findUser = userService.findUserByEmail(user.getEmail());
? ? ? ? if (findUser != null) {
? ? ? ? ? ? user.setId(findUser.getId());
? ? ? ? } else {
? ? ? ? ? ? throw new RuntimeException("注冊用戶失敗");
? ? ? ? }
? ? ? ? //注冊成功后逆粹,發(fā)送賬戶激活鏈接
? ? ? ? httpSession.setAttribute("user", user);
? ? ? ? EmailUtils.sendAccountActivateEmail(user);
? ? ? ? try {
? ? ? ? ? ? response.setContentType("text/html;charset=utf-8");
? ? ? ? ? ? response.getWriter().write("激活郵件已經(jīng)發(fā)送募疮,請注意提醒查收");
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
? ? @RequestMapping("/activate")
? ? public void activate(String id, String checkCode, HttpServletResponse response) {
? ? ? ? int idInt = Integer.parseInt(id);
? ? ? ? //根據(jù)用戶id查找用戶
? ? ? ? User user = userService.findUserById(idInt);
? ? ? ? //驗(yàn)證無誤,狀態(tài)更改為1僻弹,即激活
? ? ? ? if (GenerateLinkUtils.verifyCheckcode(user, checkCode)) {
? ? ? ? ? ? //修改狀態(tài)
? ? ? ? ? ? int activated = 1;
? ? ? ? ? ? userService.updateActivated(activated, idInt);
? ? ? ? ? ? user.setActivated(true);
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? response.setContentType("text/html;charset=utf-8");
? ? ? ? ? ? ? ? response.getWriter().write("恭喜阿浓,激活成功!");
? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
3:service類
package com.chinasofti.service;
import com.chinasofti.dao.UserDao;
import com.chinasofti.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
? ? @Autowired
? ? private UserDao userDao;
? ? public void saveUser(User user) {
? ? ? ? userDao.saveUser(user);
? ? }
? ? public User findUserByEmail(String email) {
? ? ? ? return? userDao.findUserByEmail(email);
? ? ? ?
? ? }
? ? public User findUserById(int idInt) {
? ? ? ? return? userDao.findUserById(idInt);
? ? }
? ? public void updateActivated(int activated, int idInt) {
? ? ? ? userDao.updateActivated(activated,idInt);
? ? }
}
4:dao層
package com.chinasofti.dao;
import com.chinasofti.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
? ? @Autowired
? ? private UserMapper userMapper;
? ? public User findUserByEmail(String email) {
? ? ? ? return? userMapper.findUserByEmail(email);
? ? }
? ? public User findUserById(int idInt) {
? ? ? ? return? userMapper.findUserById(idInt);
? ? }
? ? public void saveUser(User user) {
? ? ? ? userMapper.saveUser(user);
? ? }
? ? public void updateActivated(int activated, int idInt) {
? ? ? ? userMapper.updateActivated(activated,idInt);
? ? }
}
5:register.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>
? ? <title>注冊</title>
</head>
<body>
<form action="/email/regist" method="post">
? ? <table>
? ? ? ? <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="email"/></td></tr>
? ? ? ? <tr><td colspan="2"><input type="submit" value="注冊"/></td></tr>
? ? </table>
</form>
</body>
</html>
</body>
</html>
6:User實(shí)體類
package com.chinasofti.pojo;
public class User {
? ? private int id;
? ? private String username;
? ? private String password;
? ? private String email;
? ? private boolean activated;? //賬號狀態(tài)
? ? private String codeUrl;? ? ? //激活鏈接中的隨機(jī)碼
? ? public int getId() {
? ? ? ? return id;
? ? }
? ? public void setId(int id) {
? ? ? ? this.id = id;
? ? }
? ? 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 getEmail() {
? ? ? ? return email;
? ? }
? ? public void setEmail(String email) {
? ? ? ? this.email = email;
? ? }
? ? public boolean isActivated() {
? ? ? ? return activated;
? ? }
? ? public void setActivated(boolean activated) {
? ? ? ? this.activated = activated;
? ? }
? ? public String getCodeUrl() {
? ? ? ? return codeUrl;
? ? }
? ? public void setCodeUrl(String codeUrl) {
? ? ? ? this.codeUrl = codeUrl;
? ? }
}
? 7:mapper.xml文件
? ?
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
? ? ? ? PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
? ? ? ? "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- mapper節(jié)點(diǎn)必須指定namespace -->
<mapper namespace="com.chinasofti.dao.UserMapper">
? ? <!-- 指定屬性與列的對應(yīng)關(guān)系 -->
? ? <resultMap id="userMapper" type="com.chinasofti.pojo.User">
? ? ? ? <result property="id" column="id"></result>
? ? ? ? <result property="username" column="username"></result>
? ? ? ? <result property="password" column="passwordv"></result>
? ? ? ? <result property="email" column="email"></result>
? ? ? ? <result property="activated" column="activated"></result>
? ? ? ? <result property="codeUrl" column="codeUrl"></result>
? ? </resultMap>
? ? <insert id="saveUser">
? ? ? ? INSERT? INTO users VALUES (#{id},#{username},#{password},#{email},#{activated},#{codeUrl})
? ? </insert>
? ? <select id="findUserByEmail" resultMap="userMapper">
? ? ? ? SELECT? * FROM? users WHERE? email=#{email}
? ? </select>
? ? <select id="findUserById" resultMap="userMapper">
? ? ? ? SELECT? * from users WHERE? id=#{idInt}
? ? </select>
? ? <update id="updateActivated">
? ? ? ? UPDATE users SET activated=#{activated} WHERE? id=#{idInt}
? ? </update>
? ? </mapper>
8:EmailUtils工具類:
package com.chinasofti.util;
import com.chinasofti.pojo.User;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class EmailUtils {
? ? private static final String FROM = "zhouliangmet@163.com";
? ? public static void sendAccountActivateEmail(User user) {
? ? ? ? Session session = getSession();
? ? ? ? MimeMessage message = new MimeMessage(session);
? ? ? ? try {
? ? ? ? ? ? message.setSubject("這是一封激活賬號的郵件");
? ? ? ? ? ? message.setSentDate(new Date());
? ? ? ? ? ? //setFrom 表示用哪個(gè)郵箱發(fā)送郵件
? ? ? ? ? ? message.setFrom(new InternetAddress(FROM));
? ? ? ? ? ? /**
? ? ? ? ? ? * RecipientType.TO||BCC||CC
? ? ? ? ? ? *? ? TO表示主要接收人
? ? ? ? ? ? *? ? BCC表示秘密抄送人
? ? ? ? ? ? *? ? CC表示抄送人
? ? ? ? ? ? * InternetAddress? 接收者的郵箱地址
? ? ? ? ? ? */
? ? ? ? ? ? message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
? ? ? ? ? ? message.setContent("<a target='_BLANK' href='"+GenerateLinkUtils.generateActivateLink(user)+"'>"+user.getUsername()+"先生/女士您好蹋绽,請點(diǎn)擊此鏈接激活賬號"+GenerateLinkUtils.generateActivateLink(user)
? ? ? ? +"</a>","text/html;charset=utf-8");
//? ? ? ? ? ? message.setContent("<a target='_BLANK' + user.getUsername() + "先生/女士您好芭毙,請點(diǎn)擊此鏈接激活賬號" + GenerateLinkUtils.generateActivateLink(user)
//? ? ? ? ? ? ? ? ? ? + "</a>", "text/html;charset=utf-8");
? ? ? ? ? ? Transport.send(message);
? ? ? ? } catch (MessagingException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
? ? public static Session getSession() {
? ? ? ? Properties props = new Properties();
? ? ? ? props.setProperty("mail.transport.protocol", "smtp");//指定發(fā)送的郵箱的郵箱協(xié)議
? ? ? ? props.setProperty("mail.smtp.host", "smtp.163.com");//指定SMTP服務(wù)器
? ? ? ? props.setProperty("mail.smtp.port", "25");? //smtp是發(fā)信郵件服務(wù)器,端口是25
? ? ? ? props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP驗(yàn)證
? ? ? ? Session session = Session.getInstance(props, new Authenticator() {
? ? ? ? ? ? @Override
? ? ? ? ? ? protected PasswordAuthentication getPasswordAuthentication() {
? ? ? ? ? ? ? ? return new PasswordAuthentication(FROM, "98liang032");
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? return session;
? ? }
}
9:GenerateLinkUtils:
package com.chinasofti.util;
import com.chinasofti.pojo.User;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class EmailUtils {
? ? private static final String FROM = "**********@163.com";
? ? public static void sendAccountActivateEmail(User user) {
? ? ? ? Session session = getSession();
? ? ? ? MimeMessage message = new MimeMessage(session);
? ? ? ? try {
? ? ? ? ? ? message.setSubject("這是一封激活賬號的郵件");
? ? ? ? ? ? message.setSentDate(new Date());
? ? ? ? ? ? //setFrom 表示用哪個(gè)郵箱發(fā)送郵件
? ? ? ? ? ? message.setFrom(new InternetAddress(FROM));
? ? ? ? ? ? /**
? ? ? ? ? ? * RecipientType.TO||BCC||CC
? ? ? ? ? ? *? ? TO表示主要接收人
? ? ? ? ? ? *? ? BCC表示秘密抄送人
? ? ? ? ? ? *? ? CC表示抄送人
? ? ? ? ? ? * InternetAddress? 接收者的郵箱地址
? ? ? ? ? ? */
? ? ? ? ? ? message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
? ? ? ? ? ? message.setContent("<a target='_BLANK' href='"+GenerateLinkUtils.generateActivateLink(user)+"'>"+user.getUsername()+"先生/女士您好筋蓖,請點(diǎn)擊此鏈接激活賬號"+GenerateLinkUtils.generateActivateLink(user)
? ? ? ? +"</a>","text/html;charset=utf-8");
//? ? ? ? ? ? message.setContent("<a target='_BLANK' + user.getUsername() + "先生/女士您好,請點(diǎn)擊此鏈接激活賬號" + GenerateLinkUtils.generateActivateLink(user)
//? ? ? ? ? ? ? ? ? ? + "</a>", "text/html;charset=utf-8");
? ? ? ? ? ? Transport.send(message);
? ? ? ? } catch (MessagingException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
? ? public static Session getSession() {
? ? ? ? Properties props = new Properties();
? ? ? ? props.setProperty("mail.transport.protocol", "smtp");//指定發(fā)送的郵箱的郵箱協(xié)議
? ? ? ? props.setProperty("mail.smtp.host", "smtp.163.com");//指定SMTP服務(wù)器
? ? ? ? props.setProperty("mail.smtp.port", "25");? //smtp是發(fā)信郵件服務(wù)器,端口是25
? ? ? ? props.setProperty("mail.smtp.auth", "true");//指定是否需要SMTP驗(yàn)證
? ? ? ? Session session = Session.getInstance(props, new Authenticator() {
? ? ? ? ? ? @Override
? ? ? ? ? ? protected PasswordAuthentication getPasswordAuthentication() {
? ? ? ? ? ? ? ? return new PasswordAuthentication(FROM, "***********");//該地方是填寫客戶端的授權(quán)碼
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? return session;
? ? }
}
? ? ? ? 以上代碼本人已親測過退敦,能夠正常訪問粘咖,代碼較多,請耐心分析侈百,解讀N拖隆!6塾颉讽坏!