Recently in The imitation of a bookstore website: http://www.yousuu.com, the UI directly to use, the front-end back-end to write their own, most of the functions have been achieved,
The specific login registration function to share. PS: Also write login registration will not be sprayed AH =. =
I. Deployment of the development environment
Program Structure:
Bootstrap+ajax+struts2+hibernate+mysql
For reference only: to achieve the relevant functions can be
Operating system: Ubuntu 14.10
Front-End Frame: BootStrap Note: This framework is intended only to implement the user interface, with no specific features
Database: mysql-5.5 Database Tools: Emma
Servers: Tomcat Server Tools: MyEclipse 10 (STRUTS2 and hibernate environments configured)
Attention:
program debugging process may produce garbled, just keep all the tools are encoded in the same way.
Second, the project file configuration
1, new Web Project, named Root
2. Configure/webroot/web-inf/web.xml
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:// Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "> <display-name>root</ display-name> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.s Truts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> < filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </ filter-mapping> <error-page> <error-code>404</error-code> <location>/error.jsp</ location> </error-page> <error-page> <error-code>500</error-code> <location>/ error.jsp</location> </error-page> <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> </web-app>
3, configure/src/struts.xml (Struts configuration file), the other action and Interceptor was deleted by me, this is enough.
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.1//en" "http://struts.apache.org/dtds/ Struts-2.1.dtd ">
<struts>
<package name=" Default "namespace="/"extends=" Struts-default ">
<!--login-->
<action name= "Login" class= "com.action.Login" method= "Login" ></action>
<!--logout-->
<action name= "logout" class= "Com.action.Logout" method= "logout" ></action>
<!--registered-->
<action name= "register" class= "Com.action.Register" method= "register" ></action>
<!--Mail sent-->
<action name= "SendMail" class= "Com.action.SendMail" method= "SendMail" ></ action>
</package>
</struts>
4, configure/src/hibernate.cfg.xml (Hibernate database configuration file), note that the 4th line has a <mapping/> is not the need to create their own, will be configured in the next step
<?xml version= ' 1.0 ' encoding= ' UTF-8 '?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd "> <!--generated by MyEclipse hibernate Tools. --> <hibernate-configuration> <session-factory> <property name= "Myeclipse.connection.profile" >myeclipse mysql</property> <!--indicates the JDBC path, indicates the database name--> <property name= "Connection.url" >JDBC: mysql://localhost:3306/test</property> <!--Specify database account and password--> <property name= "Connection.username" > root</property> <property name= "Connection.password" >root</property> <!--indicates JDBC driver--> < Property Name= "Connection.driver_class" >com.mysql.jdbc.Driver</property> <!--specify MySQL dialect--> < Property name= "dialect" >org.hibernate.dialect.MySQLDialect</property> <property name= " Hibernate.current_session_context_class ">thread</property> <property name= "Hibernate.dialect" >org.hibernate.dialect.MySQLDialect</property> <property Name= "Show_sql" >true</property> <property name= "Format_sql" >true</property> <mapping Resource= "Com/hibernate/bookchat.hbm.xml"/> </session-factory> </hibernate-configuration>
5. Create the Com.hibernate package under the/SRC, create the Bookchat.hbm.xml under the package (Hibernate Object Relational mapping file), and configure
Note that this User class in the <class name= "Com.hibernate.User"/> is a custom database object class (Pojo) that will be configured in the next
<?xml version= "1.0"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "> <hibernate-mapping> <!--Specify the Bean class name, indicating the database table name--> <class name=" Com.hibernate.User "table=" User > <id column= "id" type= "int" > <generator class= "native"/> </ID&G
T <!--indicates the database field name, field type--> <property name= "user_id" column= "user_id" type= "int"/> <property name= "Phone" col umn= "Phone" type= "int"/> <property name= "email" column= "Email" type= "string"/> <property "name=" column= "username" type= "string"/> <property name= "password" column= "password" type= "string"/> <property
Name= "icon" column= "icon" type= "string"/> <property name= "description" column= "description" type= "string"/> <property name= "Followthreadnum" column= "Followthreadnum" type= "int"/> <property "name=" FollowPeopleNum Umn= "FollowpEoplenum "type=" "/> <property name=" Fansnum "column=" Fansnum "type=" int "/> <property name=" HAVEMSG "C Olumn= "havemsg" type= "int"/> </class> </hibernate-mapping>
6,/SRC under the Com.hibernate package to create the user class
Package com.hibernate; public class User {private int user_id;//user_id private int phone in the database;//mobile phone number private String email;//Mail Private S Tring username; User name private String password; Password private String icon; User Avatar private String description; Custom description private int followthreadnum; Concern book quantity private int followpeoplenum; The number of people concerned is private int fansnum; Number of fans private int havemsg;
Whether there is currently a new message public User () {super (); }//This constructor is useful when registering with public user (string email, string username, string password) {//User content: Username,password,email//
System definition: user_id,icon,followthreadnum,followpeoplenum,fansnum,havemsg//Leave blank: phone,description, this.user_id = 39212;
This.phone = phone;
This.email = email;
This.username = Username;
This.password = password;
This.icon = "Images/icon.png";
this.description = description;
This.followthreadnum = 0;
This.followpeoplenum = 0;
This.fansnum = 0;
this.havemsg = 0;
public int getuser_id () {return user_id; } public void setuser_id (int user_id) {this.user_id = user_id;
public int Getphone () {return phone;
public void Setphone (int phone) {this.phone = phone;
Public String Getemail () {return email;
public void Setemail (String email) {this.email = email;
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 GetIcon () {return icon;
public void SetIcon (String icon) {This.icon = icon;
Public String GetDescription () {return description;
} public void SetDescription (String description) {this.description = description;
public int Getfollowthreadnum () {return followthreadnum;
The public void setfollowthreadnum (int followthreadnum) {this.followthreadnum = Followthreadnum; public int Getfollowpeoplenum () {return followpeopLenum;
The public void setfollowpeoplenum (int followpeoplenum) {this.followpeoplenum = Followpeoplenum;
public int Getfansnum () {return fansnum;
The public void setfansnum (int fansnum) {this.fansnum = Fansnum;
public int gethavemsg () {return havemsg;
The public void sethavemsg (int havemsg) {this.havemsg = havemsg;
}
}
7, under the/SRC under the Com.db package to create the CreateTable class, then run As-java application, see whether the console output SQL statements
Package com.db;
Import org.hibernate.cfg.Configuration;
Import Org.hibernate.tool.hbm2ddl.SchemaExport;
public class Creattabledonot {public
static void Main (string[] args) {
//default read Hibernate.cfg.xml file
Configuration cfg = new Configuration (). Configure ();
Schemaexport export = new Schemaexport (CFG);
Export.create (True, true);
}
Third, check the database
1, open the database GUI tool to see if the test database has a user table, if you can open the user table description before the configuration successfully.
2, edit the user table: Set the default value of the field, you can add data to the table.
Four, Web page UI design
1, we in the Struts.xml file configuration has been buried foreshadowing:
<action name= "Login" class= "com.action.Login" method= "Login" ></action>
<action name= "Logout" class= "Com.action.Logout" method= "Logout" ></action>
<action name= "register" class= "Com.action.Register" method= "register" ></action>
<action name= "SendMail" class= "Com.action.SendMail" method= "SendMail" ></action>
We can request/login,/logout,/register in the Web page to access these three action processing classes, of course, these three categories of specific content we have not written, first put.
2, now start thinking about what the web design needs ...
<1> Home provide login and registration links
<2> Login pop-up box and registration page
<3> Login/Registration Success, login and registration disappear, display username and exit login
<4> we want to achieve the effect: Login/Registration After the successful display of user name, login failure dynamic prompts error details!
Five, Jquery+ajax design
1, the main jquery and Ajax code
(Function (window, $) {var Sokk = {};
Ys.common = Sokk;
Mailbox Authentication sokk.sendmail = function () {var email = $ ("#inputEmail"). Val (). Trim ();
if (!checkemail (email)) {return false;
///Send Request $.get ("/sendmail", "email=" +email,function (data) {data = Json.parse (data);
Tip (Data.code);
}///Register Sokk.signup = function (form) {var form = $ (form);
The successful party can continue to execute if (!checksignup ("Form.find")) return false;
Serializing the form, generating the JSON object var jstr =form.serialize ();
var jstr = json.stringify (jform);
Tip (JSTR);
$.post ("/register", jstr,function (data) {data = Json.parse (data);
if (Data.code = =) {location.reload ();//How to jump to the home page?
else {tip (data.code);
}
})
};
Login Sokk.login = function (form) {var form = $ (form);
var input = form.find ("input");
var Username=$.trim (Input[0].value);
var Password=$.trim (Input[1].value);
if (Checklogin (Username,password)) {return false;
var dataparam = {};
Dataparam.username = Username; DataParam.password = password;
The Dataparam here is a key-value pair, but the server gets the?username=xx&password=xx; If you use JSON transfer then you cannot use $.ajax in this way, and JSON will be parsed on the server side,//So JSON is not recommended when sending requests.
Accept data can use JSON $.post ("/login", Dataparam, function (data) {//JSON string->json Object data = json.parse (data);
if (Data.code = =) {location.reload ();
else {tip (data.code);
}
})
};
Logout sokk.logout = function () {$.get ("/logout", function (data) {//json string->json object data = json.parse (data);
if (data.code==200) {location.reload ();
}
})
}; }) (window, $)
2, custom tool code
Custom prompt function Tip (info) {if (isNaN (info)) {toastr.info (info);
}else{var msg; if (info<300) {switch (info) {case 100:msg= "to join the Bookshelf successfully!" ";
Break Case 101:msg= "pay attention to the success of this book!" ";
Break Case 102:msg= "has moved to" is watching "! ";
Break Case 103:msg= "has moved to" ready to see! " ";
Break Case 104:msg= "has been moved to read!" ";
Break Case 105:msg= "has been moved to the Recycle Bin!" ";
Break Case 110:msg= "Verify that the message has been sent to your mailbox!"
"; Case 200:msg= "Request successful!" ";
Break Case 202:msg= "The request has been accepted but has not been processed. ";
Break Case 204:msg= "request succeeded, but no return content." ";
Break
Default:break;
Toastr.success (msg); }else if (info<1000) {switch (info) {case 301:msg=] The location of the request page changed! ";
Break Case 400:msg= "Error request, please enter the correct information!" ";
Break Case 401:msg= "Illegal request, unauthorized access to this page!" ";
Break Case 403:msg= "Reject request!" ";
Break Case 404:msg= "Request page does not exist!" ";
Break Case 408:msg= "Request timed out!" ";
Break Case 500:msg= "Server Error! ";
Break Case 500:msg= "Service not available!" ";
Break Case 900:msg= "username/password error, please re-enter";
Break Case 903:msg= "Server error, please try again!" ";
Break Case 904: msg= "Server no return information!" ";
Break Case 905:msg= "Network error! ";
Break Case 906:msg= "registration failed, please try again!"
"; Case 907:msg= "Mailbox Authentication code Error!
"; Case 908:msg= "user name already exists!"
"; Case 909:msg= "Mailbox has been registered!
"; Case 910:msg= "Verify message delivery failed!"
";
Default:break;
Toastr.error (msg);
}else{Toastr.info (info);
Check function Checksignup (input) {var username = $.trim (input[0].value);
var password1 = $.trim (Input[1].value);
var password2 = $.trim (Input[2].value);
var email = $.trim (input[3].value);
var emailcode = $.trim (Input[4].value); for (var i = 0; i < input.length i++) {if (input[i].value.length<=0) {tip ("All content must not be empty!")
");
return false;
}
}; if (username.length<4) {tip ("User name must not be less than 4 characters!")
");
return false; } if (Password1!==password2) {tip ("two times entered a different password!")
");
return false; } if (password1.length<6) {tip ("Password must not be less than 6 characters!")
");
return false;
return true; function Checklogin (Username,password) {if (!username) {Tip ("Enter user name!")
"); return false;
} if (!password) {tip ("Enter password!")
");
return false; } function Checkemail (email) {var reg =/^ ([a-za-z0-9]+[_|\_|\.]?) *[a-za-z0-9]+@ ([a-za-z0-9]+[_|\_|\.]?) *[a-za-z0-9]+\. [A-za-z]
{2,3}$/;
if (email) {if (reg.test (email)) {return true; }else{Tip ("The mailbox address does not conform to the specification!")
");
return false; }else{Tip ("Mailbox address must not be empty!")
");
return false;
}
}
3, Toastr is a front-end non-blocking prompt plug-ins, can be downloaded to the http://www.bootcdn.cn/toastr.js/use
Six, Action design
1, Login.java
Package com.action;
Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
Import Com.service.BaseService;
Import Com.service.BaseServiceImpl;
Import Com.util.OperateJSON;
public class Login extends Actionsupport {private static final long serialversionuid = 4679952956618457478L;
Private String username;
private String password;
public void Login () {HttpServletRequest request = Servletactioncontext.getrequest ();
Baseservice hs = new Baseserviceimpl ();
Operatejson OJ = new Operatejson ();
Username = Request.getparameter ("username");
Password = request.getparameter ("password");
System.out.println ("Username:" + username + "--Password:" + password);
Login return User id Object obj = hs.login (username, password);
if (obj!= null) {System.out.println ("username password is correct");
Request.getsession (). setattribute ("username", username);
Request.getsession (). setattribute ("userid", obj); System.out.println ("User name" + Username + "Session set finished ~");
SYSTEM.OUT.PRINTLN ("User ID session set finished ~");
Oj.putcode (200);
else {System.out.println ("Username password error");
Oj.putcode (900);
} oj.send (); }
}
2, Logout.java
Package com.action;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
Import Com.util.OperateJSON;
public class Logout extends Actionsupport {
private static final long serialversionuid = -6758897982192371466l;
HttpServletRequest request = Servletactioncontext.getrequest ();
HttpServletResponse response = Servletactioncontext.getresponse ();
Operatejson OJ = new Operatejson ();
public void Logout () {
request.getsession (). RemoveAttribute ("username");
Request.getsession (). invalidate ();
if (Request.getsession (). getattribute ("username") = = null) {
oj.putcode;
} else {
Oj.putcode (903 );
}
Oj.send ();
}
3, Register.java
Package com.action;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.struts2.ServletActionContext;
Import Com.hibernate.User;
Import Com.opensymphony.xwork2.ActionSupport;
Import Com.service.BaseService;
Import Com.service.BaseServiceImpl;
Import Com.util.OperateJSON;
public class Register extends Actionsupport {private static final long serialversionuid = -3356620731966076779l;
HttpServletRequest request = Servletactioncontext.getrequest ();
HttpServletResponse response = Servletactioncontext.getresponse ();
Baseservice bs = new Baseserviceimpl ();
Operatejson OJ = new Operatejson ();
SendMail sm = new SendMail ();
public void Register () {String username = request.getparameter ("username");
String Password1 = Request.getparameter ("Password1");
String Password2 = Request.getparameter ("Password2");
String Password = (password1.equals (password2)? password1:null);
String email = request.getparameter ("email"); String Emailcode = Request.getparameter ("Emailcode"); Determines whether user input and generated mailbox authentication codes are the same if (!
Emailcode.equals (Sm.getmailcode ())) {Oj.putcode (907);
Oj.send ();
Return
//Detect username/mailbox is unique if (!bs.isunique ("User", "username", username)) {oj.putcode (908);
Oj.send ();
Return
} if (!bs.isunique ("User", "email", email)) {Oj.putcode (909);
Oj.send ();
Return
//Build User Object User user = new user (email, username, password);
Establish the Object relational mapping Boolean reged = bs.register (user);
if (reged) {System.out.println ("User registration succeeded");
Request.getsession (). setattribute ("username", username);
Oj.putcode (200);
else {System.out.println ("registration failed");
Oj.putcode (906);
} oj.send (); }
}
4, sendmail.java SMTP protocol Send mail class, need to import mail jar package before use, also set up the SMTP service for inspiring people's mailbox
Package com.action;
Import Java.util.Date;
Import java.util.Properties;
Import Javax.mail.BodyPart;
Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import Javax.mail.Multipart;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeBodyPart;
Import Javax.mail.internet.MimeMessage;
Import Javax.mail.internet.MimeMultipart;
Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
Import Com.util.OperateJSON;
public class SendMail extends Actionsupport {private static final long serialversionuid = -4724909293302616101l; private static String QQ = "392102018"; QQ private static String HOST = "qq.com"; SMTP server host name private static String pass = "xxxxxxxx"; SMTP server password private static String Mailcode;
Message authentication code Operatejson OJ = new Operatejson (); public void SendMail () {HttpServletRequest request = Servletactioncontext.getrequest ();
String email = request.getparameter ("email");
SYSTEM.OUT.PRINTLN (email);
String Mailcode = Sendmail.setmailcode ();
try {beginsend (email, mailcode);
Oj.putcode (110);
catch (Messagingexception e) {oj.putcode (910);
finally {oj.send ();
The public static String Setmailcode () {Mailcode = 100000 + (int) (Math.random () * 900000) + BC;
System.out.println (Mailcode);
return mailcode;
Public String Getmailcode () {return sendmail.mailcode; public void BeginSend (string email, string mailcode) throws Messagingexception {string mailTo = email;//Inbox Mail Address String Mailtitle = "Welcome to use the book Chat network!"
Activate your account Now "; String mailcontent = "<p> respected user:</p><p> Hello! Activate your account now, and read and exchange books with your online members. To activate your account, simply copy the following verification code to the registration page for confirmation. </p> "+ mailcode +" <p> copyright ©1999-2015 bookchat. All rights reserved.
</p> ";
Set main information Properties props = new properties ();
Props.put ("Mail.smtp.host", "SMTP." + host); Props.put ("Mail.smtp.auth", "trUE ");
Session session = Session.getinstance (props);
Session.setdebug (TRUE);
Open the Mail object mimemessage message = new MimeMessage (session);
Set sender/Recipient/subject/letter time internetaddress from = new InternetAddress (QQ + "@" + HOST);
Message.setfrom (from);
InternetAddress to = new InternetAddress (mailTo);
Message.setrecipient (Message.RecipientType.TO, to);
Message.setsubject (Mailtitle);
Message.setsentdate (New Date ()); Sets the Message object content bodypart MDP = new MimeBodyPart ()//Creates a new BodyPart object that holds the contents of the letter mdp.setcontent (mailcontent, "text/html;charset=u
Tf-8 ")//set content and Format/encoding for BodyPart objects Multipart mm = new Mimemultipart ();//Create a new Mimemultipart object to hold the BodyPart object (in fact, can hold more than one)
Mm.addbodypart (MDP);//Add BodyPart to Mimemultipart object (can add more bodypart) message.setcontent (mm);//mm as the content of the Message object
Message.savechanges ();
Open the Transfer object transport transport = Session.gettransport ("SMTP"); Transport.connect ("SMTP." + HOST, QQ, pass);
Here's 115798090 also to be modified for your QQ number transport.sendmessage (message, message.getallrecipients ()); transport.clOSE ();
}
}
5, Opreatejson
Package com.util;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Org.apache.struts2.ServletActionContext;
Import Net.sf.json.JSONObject;
public class Operatejson {Jsonobject json;
Public Operatejson () {json = new jsonobject ();
Json.put ("Code", "");
Json.put ("msg", "");
Json.put ("Data", "");
Public Operatejson (String str) {JSON = Jsonobject.fromobject (str);
public void put (String key, Object value) {json.remove (key);
Json.put (key, value);
The public void Putcode (Object value) {json.remove ("code");
This.put ("code", value);
public void Putmsg (Object value) {Json.remove ("msg");
This.put ("MSG", value);
public void Remove (String key) {json.remove (key);
The public void Send () {System.out.println ("----------returned data is:" + json);
try {printwriter out = Servletactioncontext.getresponse (). Getwriter ();
Out.print (JSON);
Out.flush ();
catch (IOException e) {e.printstacktrace ();
}
}
}
Seven, Hibernate DAO design
This piece is a number of operations database content, we all have their own style, a little more careful to write. The code is too messy, I don't put it out to scare-.-! 。
Viii. Summary
Start to show the results of the or forget it, it is so. A small example, the flaws are unavoidable, but also hope the great God to correct me.
Finished, the mood is much better, the job fair to see or not to find work is not important, it is important that I walk in the right way, only rely on their own is the strong ...