Spring + hibernate + freemarker + jquery login registration example

Source: Internet
Author: User
Tags log log valid email address

When learning a new content, I will look for some examples. However, some examples seem incomplete, some SQL table creation statements do not exist, and sometimes there is no jar package. I feel like, there are a lot of obstacles for beginners, So I first put the directory structure of the project out, then put the SQL tabulation statement, and finally put the source code:

Directory structure:

2. Table creation statement:

MySQL database, test database:

create table 'users'(id int(10) unsigned not null auto_increment,name varchar(45) not null,psw varchar(45) not null,email varchar(32) default null,primary key(id))

The idea and annotation function of spring MVC can play the role of struts to process the business logic. At the same time, Spring provides the freemarker template and the hibernate interface. Therefore, freemarker is displayed on the front-end, hibernate performs background database processing. jquery implements registration verification. In this example, jquery Ajax is also used to verify that the logon username and password are correct. The returned information is displayed on this page.

I. First, introduce spring configuration in 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>loginTest</display-name>  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext*.xml</param-value>  </context-param>  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <servlet>    <servlet-name>spring</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>spring</servlet-name>    <url-pattern>*.do</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.ftl</welcome-file>  </welcome-file-list></web-app>

2. spring-servlet.xml configuration, configure freemarker here:

<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: P = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop HTTP: // Www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <context: annotation-config/> <! -- Convert the class marked with @ controller annotation to Bean --> <context: component-scan base-package = "com. MVC. Controller"/> <! -- Start the annotation function of spring MVC to map requests and pojo annotations --> <Bean class = "org. springframework. Web. servlet. MVC. annotation. annotationmethodhandleradapter"/> <! -- Resolve the Model View name, that is, add the prefix suffix to the model view name --> <! -- Set the configuration file path of freemarker --> <bean id = "freemarkerconfiguration" class = "org. springframework. beans. factory. config. propertiesfactorybean "> <property name =" location "value =" classpath: freemarker. properties "/> </bean> <! -- Configure the freemarker template path --> <bean id = "freemarkerconfig" class = "org. springframework. Web. servlet. View. freemarker. freemarkerconfigurer"> <! -- Property name = "freemarkersettings" ref = "freemarkerconfiguration"/--> <property name = "templateloaderpath"> <value>/WEB-INF/FTL/</value> </property> <property name = "freemarkervariables"> <map> <Entry key = "xml_escape" value-ref = "fmxmlescape"/> </map> </property> </bean> <Bean id = "fmxmlescape" class = "freemarker. template. utility. xmlescape "/> <! -- Configure the freemarker view parser --> <! -- Freemarker view Parsing is returned as student .. Configure the suffix FTL and view parser here .. --> <Bean id = "viewresolver" class = "org. springframework. web. servlet. view. freemarker. freemarkerviewresolver "> <property name =" viewclass "value =" org. springframework. web. servlet. view. freemarker. freemarkerview "> </property> <property name =" suffix "value = ". FTL "/> <property name =" contenttype "value =" text/html; charset = UTF-8 "/> <property name =" exposerequestattributes "value =" true "/> <property name =" expose Sessionattributes "value =" true "/> <property name =" exposespringmacrohelpers "value =" true "/> </bean> <! -- FM --> </beans>

3. Configure applocationcontext. xml and configure hibernate:

<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: AOP = "http://www.springframework.org/schema/aop" xmlns: context = "http://www.springframework.org/schema/context" xmlns: P = "http://www.springframework.org/schema/p" xmlns: Tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://www.springframework.org/schema/beans http: // ww Http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <context: annotation-config/> <Context: component-scan base-package = "com. MVC"/> <! -- Automatically scans all annotations for this path --> <context: Property-placeholder location = "classpath:/hibernate. properties "/> <bean id =" sessionfactory "class =" org. springframework. orm. hibernate3.annotation. annotationsessionfactorybean "> <property name =" datasource "ref =" datasource "/> <property name =" hibernateproperties "> <props> <prop key =" hibernate. dialect ">$ {datasource. dialect} </prop> <prop key = "hibernate. hbm2ddl. auto "> $ {datasource. HBM 2ddl. auto} </prop> <prop key = "hibernate. hbm2ddl. auto "> Update </prop> </props> </property> <property name =" packagestoscan "> <list> <value> COM. MVC. entity </value> <! -- Scan the object class, that is, the model --> </List> </property> </bean> <bean id = "transactionmanager" class = "org. springframework. orm. hibernate3.hibernatetransactionmanager "> <property name =" sessionfactory "ref =" sessionfactory "/> <property name =" datasource "ref =" datasource "/> </bean> <bean id =" datasource "class =" org. springframework. JDBC. datasource. drivermanagerdatasource "> <property name =" driverclassname "value =" $ {Objective C E. driverclassname} "/> <property name =" url "value =" $ {datasource. URL} "/> <property name =" username "value =" $ {datasource. username} "/> <property name =" password "value =" $ {datasource. password} "/> </bean> <! -- DAO implementation --> <bean id = "entitydao" class = "com. MVC. dao. entitydaoimpl "> <property name =" sessionfactory "ref =" sessionfactory "/> </bean> <TX: annotation-driven transaction-Manager =" transactionmanager "/> <TX: annotation-driven mode = "aspectj"/> <AOP: aspectj-autoproxy/> </beans>

4. The above configuration reads two properties files, one of which is Hibernate and the other is freemarker:

Hibernate. properties:

dataSource.password=111111dataSource.username=rootdataSource.databaseName=testdataSource.driverClassName=com.mysql.jdbc.DriverdataSource.dialect=org.hibernate.dialect.MySQL5DialectdataSource.serverName=localhost:3306dataSource.url=jdbc:mysql://localhost:3306/testdataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password}dataSource.hbm2ddl.auto=update

Freemarker. properties:

tag_syntax=auto_detecttemplate_update_delay=2default_encoding=UTF-8output_encoding=UTF-8locale=zh_CNdate_format=yyyy-MM-ddtime_format=HH:mm:ssdatetime_format=yyyy-MM-dd HH:mm:ss

5. so far, all the frameworks have been configured. jquery is left. download the file and put it in the JS folder. verification is also used in the example. Therefore, jquery is also required. validate. JS file.

6. For the logic processing and data processing part, put the tool method into baseservice. java. In this way, each different application can directly use the method in it and pass different parameters to implement it.

Baseservice. Java:

package com.mvc.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.mvc.dao.EntityDao;@Servicepublic class BaseService {@Autowiredprivate EntityDao entityDao;@Transactionalpublic List<Object> getAllList(String tableSimpleName){StringBuffer sff = new StringBuffer();sff.append("select a from ").append(tableSimpleName).append(" a ");List<Object> list = entityDao.createQuery(sff.toString());return list;}/** * find the list of entity by where conditions  * @param tableSimpleName * @param columns * @param values * @return  list */public List<Object> findByWhere(String tableSimpleName,String[] columns,String[] values){StringBuffer sb = new StringBuffer();sb.append("select a from ").append(tableSimpleName).append( " a where ");if(columns.length==values.length){for(int i = 0; i < columns.length; i++){sb.append("a.").append(columns[i]).append("='").append(values[i]).append("'");if(i < columns.length-1){sb.append(" and ");}}List<Object> list = entityDao.createQuery(sb.toString());return list.size()>0?list:null;}else{return null;}}/** * save * @param obj */public void save(Object obj){entityDao.save(obj);}/** * delete * @param obj */public void delete(Object obj){entityDao.delete(obj);}/** * update * @param obj */public void update(Object obj){entityDao.update(obj);}}

Userservice. Java:

package com.mvc.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;@Servicepublic class UsersService extends BaseService {@Autowired@Transactionalpublic List<Object> getAllList(){List<Object> list = getAllList("com.mvc.entity.Users");return list;}public boolean isExist(String username, String password){List<Object> list = findByWhere("com.mvc.entity.Users", new String[]{"user","psw"}, new String[] {username,password});return list!=null?true:false;}}

6. It is not difficult to understand the controller if struts is used:

Logincontroller. Java:

package com.mvc.controller;import javax.servlet.http.HttpServletRequest;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import com.mvc.service.UsersService;@Controllerpublic class LoginController {protected final transient Log log = LogFactory.getLog(LoginController.class);@Autowiredprivate UsersService usersService;public LoginController(){}@RequestMapping("/login.do")public String load(HttpServletRequest request,ModelMap modelMap){String username = request.getParameter("username");String password = request.getParameter("password");boolean isExist = usersService.isExist(username, password);if(isExist){modelMap.addAttribute("username", username);return "loginsuc";}return "loginerror";}//jQuery ajax check up/@RequestMapping("/check.do")public @ResponseBody   String check(              @RequestParam(value = "username", required = true) String username,             @RequestParam(value = "password", required = true) String password,             Model model) {            // boolean isExist = usersService.isExist(username, password);String info = new String();if(isExist){info = "yes";}else{info = "no";}        return info;  }}

7. The users. Java in the Entity corresponds to the database tables in a one-to-one manner through annotation:

Users. Java

package com.mvc.entity;import java.io.Serializable;import javax.persistence.Basic;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name = "users")public class Users implements Serializable {private static final long serialVersionUID = 1L;@Id@Basic(optional = false)@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id", nullable = false)private Integer id;@Column(name = "name")private String user;@Column(name = "psw")private String psw;@Column(name = "email")private String email;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUser() {return user;}public void setUser(String user) {this.user = user;}public String getPsw() {return psw;}public void setPsw(String psw) {this.psw = psw;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}

8. Front-end index. FTL uses the Ajax method to verify whether the user's meter and password are correct:

Index. FTL:

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

9. signupvalidate. JS is the form verification during registration:

$(document).ready(function() {// validate signup form on keyup and submit$("#signupForm").validate({rules: {username: {required: true,minlength: 2},password: {required: true,minlength: 5},confirm_password: {required: true,minlength: 5,equalTo: "#password"},email: {required: true,email: true},messages: {username: {required: "Please provide a password",minlength: "Your password must be at least 2 characters long"},password: {required: "Please provide a password",minlength: "Your password must be at least 5 characters long"},confirm_password: {required: "Please provide a password",minlength: "Your password must be at least 5 characters long",equalTo: "Please enter the same password as above"},email: "Please enter a valid email address",}}});});

In general, this is the case.

I tested the source code in eclipse.

Logintest.rar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.