Recently separated from the project registered mailbox activation function, tidy up, convenient for next use
1.registercontroller.java
Package Com.app.web.controller;import Java.text.parseexception;import Javax.annotation.resource;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.servlet.ModelAndView; Import Com.app.service.impl.registervalidateservice;import com.app.tools.ServiceException; @Controllerpublic class Registercontroller {@Resource private registervalidateservice service; @RequestMapping (value= "/user/register", method={requestmethod.get,requestmethod.post}) public Modelandview load ( HttpServletRequest request,httpservletresponse response) throws parseexception{String action = Request.getparamete R ("Action"); Modelandview mav=new Modelandview (); if ("register". Equals (Action)) {//register String email = request.getparameteR ("email"); Service.processregister (email);//Email Activation mav.addobject ("text", "registration successful"); Mav.setviewname ("register/register_success"); } else if ("Activate". Equals (Action)) {//activate String email = request.getparameter ("email");//Received Fetch email String validatecode = request.getparameter ("Validatecode");//Activation code try {Service . processactivate (email, validatecode);//Invoke Activation method Mav.setviewname ("register/activate_success"); } catch (Serviceexception e) {request.setattribute ("message", E.getmessage ()); Mav.setviewname ("Register/activate_failure"); }} return MAV; } }
2.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.stereotype.service;import Com.app.dao.userdao;import Com.app.tools.md5tool;import Com.app.tools.md5util;import Com.app.tools.SendEmail; Import Com.app.tools.serviceexception;import Com.code.model.UserModel; @Servicepublic class Registervalidateservice {@Autowired private Userdao Userdao; /** * Processing Registration */public void Processregister (String email) {Usermodel user=new usermodel (); Long as=5480l; User.setid (AS); User.setname ("Xiaoming"); User.setpassword ("324545"); User.setemail (email); User.setregistertime (New Date ()); User.setstatus (0); If you are in a secure, can be the activation code processing more complex points, here I do a little bit simple processing//user.setvalidatecode (md5tool.md5encrypt (email)); User.setvalidatecode (Md5util.encode2hex (email)); Userdao.save (user);//Save registration Information//e-mail contents StrIngbuffer sb=new StringBuffer ("Click the link below to activate the account, 48 hours, or re-register the account, the link can only be used once, please activate as soon as possible!") </br> "); Sb.append ("<a href=\" http://localhost:8080/springmvc/user/register?action=activate&email= "); Sb.append (email); Sb.append ("&validatecode="); Sb.append (User.getvalidatecode ()); Sb.append ("\" >http://localhost:8080/springmvc/user/register?action=activate&email= "); Sb.append (email); Sb.append ("&validatecode="); Sb.append (User.getvalidatecode ()); Sb.append ("</a>"); Send mail sendemail.send (email, sb.tostring ()); SYSTEM.OUT.PRINTLN ("Send Mail"); , String Validatecode) throws Serviceexception, parseexception{//data access layer, get user information via email usermodel user=user Dao.find (email); Verify if the user exists if (user!=null) {//Verify User Activation status if (User.getstatus (==0) {////Not activated date CurrentTime = new Date ();//Get current time//verify link is expired Currenttime.before (User.getregistertime ()); if (Currenttime.before (User.getlastactivatetime ())) {//Verify that the activation code is correct if (validatecode . Equals (User.getvalidatecode ())) {//Activate successfully,//and update user's activation status for activated SYSTEM.OUT.P Rintln ("==sq===" +user.getstatus ()); User.setstatus (1);//Change the state to activate System.out.println ("==sh===" +user.getstatus ()); Userdao.update (user); } else {throw new serviceexception ("Incorrect activation Code"); }} else {throw new serviceexception ("The Activation code has expired! "); }} else {throw new Serviceexception ("The mailbox is activated, please log in!") "); }} else {throw new Serviceexception ("The mailbox is not registered (the mailbox address does not exist)! "); } }}
3.usermodel.java
Package Com.code.model;import Java.beans.transient;import Java.util.calendar;import Java.util.date;public class Usermodel {private Long ID; private string name; private string password; private string email;//registered account private int stat us=0;//activation State Private String validatecode;//Activation Code private Date registertime;//Registration time/////////////////public long ge TId () {return id; } public void SetId (Long id) {this.id = ID; } public String GetName () {return name; } public void SetName (String name) {this.name = name; } 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 int GetStatus () {return status; } public void SetStatus (int status) {this.status = status; } public String GetvalidatecodE () {return validatecode; } public void Setvalidatecode (String validatecode) {this.validatecode = Validatecode; Public Date Getregistertime () {return registertime; } public void Setregistertime (Date registertime) {this.registertime = Registertime; }/////////////////////////@Transient public Date getlastactivatetime () {Calendar cl = Calendar.getinsta NCE (); Cl.settime (Registertime); Cl.add (Calendar.date, 2); return Cl.gettime (); }}
4.sendemail.java
Package Com.app.tools;import Java.util.date;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.internetaddress;import Javax.mail.internet.mimemessage;public class SendEmail {public static final String HOST = "smtp.163.com"; public static final String PROTOCOL = "SMTP"; public static final int PORT = 25; public static final String from = "[email protected]";//sender's email public static final String PWD = "123456";//Sender Secret Code/** * Get Session * @return */private static Session getsession () {Properties props = new Prope Rties (); Props.put ("Mail.smtp.host", host);//Set the server address Props.put ("Mail.store.protocol", protocol);//Set Protocol props.put ("Ma Il.smtp.port ", port);//Set Port Props.put (" Mail.smtp.auth ", true); Authenticator Authenticator = new Authenticator () {@Override protected passwordauthentication getpasswordauthentication () { return new Passwordauthentication (from, PWD); } }; Session session = Session.getdefaultinstance (props, authenticator); return session; public static void Send (String toemail, string content) {Session session = GetSession (); try {System.out.println ("--send--" +content); Instantiate a message message msg = new MimeMessage (session); Set Message Attributes Msg.setfrom (new InternetAddress (from)); Internetaddress[] Address = {new InternetAddress (Toemail)}; Msg.setrecipients (Message.RecipientType.TO, address); Msg.setsubject ("Account activation Email"); Msg.setsentdate (New Date ()); Msg.setcontent (Content, "text/html;charset=utf-8"); Send the Message transport.send (msg); } catch (Messagingexception Mex) {mex.printstacktrace (); } }}
5.jsp page
registeremailvalidae.jsp
register_success.jsp
<body> Congratulations on your successful registration! Please click on the link to register the email to activate! </body>
ACTIVATE_SUCCESS.JSP:
<body> Account activation success, click here to login! </body>
ACTIVATE_FAILURE.JSP:
<body> activation failed! Error message: ${message}</body>
Java implementation when registering to send activation Mail + activation