基于Spring的网站注册登录系统

1. Domain:


系统使用了4个类:User(用户)、UserList(保持多个User的链表)、Role(用户的角色)和 Address(用户的地址信息)。

User:User类定义前使用了3个注释(Annotation):@Entity用于说明User本身是一个实体,对应到数据库的一个表格;@Table(name="User")用于说明了数据库表格的名字,不使用@Table(name="User")的话表格的名字和类名保持一致,即User;@Cache注释说明了对数据库表USER进行读写缓存,本文使用了EhCache作为数据库的二级缓存。

用户类包含了下列成员信息:id、firstname、lastname、username、sex、email、password、address、role、confirmed、create和update。

id:该成员使用了@Id、@GeneratedValue、@Column注释。@Id用户说明该成员为USER表的identity列;@GeneratedValue说明该列的值由数据库自动产生;@Column用于自定义该成员在数据库表格中的列名,不使用@Column,数据库表格列名和该成员名保持一致,这一点@Column和上面提到的@Table作用类似。

firstname、lastname:这两个成员都是使用了@Column的nullable = false,说明当向数据库表格插入数据时该成员对应的列不能为空,为空的话数据插入失败。

username:unique = true 说明了数据库中不能存放相同username的记录;updatable = false说明记录一旦插入数据库表格,该值不能进行修改。

address:@ManyToMany定义了User和Address间多对多的映射关系,cascade = CascadeType.ALL说明当USER表格插入一条含有新address的记录时,ADDRESS表格也会自动插入新的记录。@JoinTable用于说明为表格USER和ADDRESS创建一个连接表。

confirmed:该成员用于标示用户注册后有没有打开发送到注册邮箱中的链接进行确认,只有确认后才算成功注册。

confirmedID:该成员是发送到注册邮箱的确认链接的一部分。

create、update:这两个成员分别表示记录的创建和修改时间,@Temporal用于说明是时间戳。注意相关函数onCreate、onUpdate及注释,@PrePersist说明当记录插入数据库时执行,@PreUpdate说明当更新记录时执行。

getCaptcha:该方法比较特殊,只是一个哑方法,用于支持验证错误信息。

  1. package com.haibin.rest.domain;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Date;  
  5. import java.util.Set;  
  6.   
  7. import javax.persistence.CascadeType;  
  8. import javax.persistence.Column;  
  9. import javax.persistence.Entity;  
  10. import javax.persistence.GeneratedValue;  
  11. import javax.persistence.GenerationType;  
  12. import javax.persistence.Id;  
  13. import javax.persistence.JoinColumn;  
  14. import javax.persistence.JoinTable;  
  15. import javax.persistence.ManyToMany;  
  16. import javax.persistence.OneToOne;  
  17. import javax.persistence.PrePersist;  
  18. import javax.persistence.PreUpdate;  
  19. import javax.persistence.Table;  
  20. import javax.persistence.Temporal;  
  21. import javax.persistence.TemporalType;  
  22.   
  23. import org.hibernate.annotations.Cache;  
  24. import org.hibernate.annotations.CacheConcurrencyStrategy;  
  25.   
  26. import com.haibin.rest.utils.HashCodeUtil;  
  27.   
  28. @Entity  
  29. @Table(name = "USER")  
  30. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  31. public class User implements Serializable {  
  32.   
  33.     private static final long serialVersionUID = 1863930026592012220L;  
  34.   
  35.     @Id  
  36.     @GeneratedValue(strategy = GenerationType.AUTO)  
  37.     @Column(name = "USER_ID")  
  38.     private long id;  
  39.   
  40.     @Column(name = "USER_FIRSTNAME", nullable = false)  
  41.     private String firstname;  
  42.   
  43.     @Column(name = "USER_LASTNAME", nullable = false)  
  44.     private String lastname;  
  45.   
  46.     @Column(name = "USER_USERNAME", nullable = false, unique = true, updatable = false)  
  47.     private String username;  
  48.   
  49.     @Column(name = "USER_SEX", nullable = false)  
  50.     private String sex;  
  51.   
  52.     @Column(name = "USER_EMAIL", nullable = false, unique = true)  
  53.     private String email;  
  54.   
  55.     @Column(name = "USER_PASSWORD", nullable = false)  
  56.     private String password;  
  57.   
  58.     @Column(name = "USER_ADDRESS")  
  59.     @ManyToMany(cascade = CascadeType.ALL)  
  60.     @JoinTable(name = "USER_ADDRESS", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ADDRESS_ID") })  
  61.     private Set<Address> address;  
  62.   
  63.     @OneToOne(cascade = CascadeType.ALL)  
  64.     private Role role;  
  65.   
  66.     @Column(name = "USER_CONFIRMED")  
  67.     private boolean confirmed;  
  68.   
  69.     @Column(name = "USER_CONFIRMED_ID", unique = true)  
  70.     private String confirmedID;  
  71.   
  72.     @Temporal(TemporalType.TIMESTAMP)  
  73.     @Column(name = "USER_CREATE", nullable = false)  
  74.     public Date create;  
  75.   
  76.     @Temporal(TemporalType.TIMESTAMP)  
  77.     @Column(name = "USER_UPDATE", nullable = false)  
  78.     private Date update;  
  79.   
  80.     public User() {  
  81.   
  82.     }  
  83.   
  84.     public User(String firstname, String lastname, String sex, String email,  
  85.             String password, Set<Address> address) {  
  86.         this.firstname = firstname;  
  87.         this.lastname = lastname;  
  88.         this.sex = sex;  
  89.         this.email = email;  
  90.         this.password = password;  
  91.         this.address = address;  
  92.     }  
  93.   
  94.     public long getId() {  
  95.         return id;  
  96.     }  
  97.   
  98.     public void setId(long id) {  
  99.         this.id = id;  
  100.     }  
  101.   
  102.     // Dummy getter to support validation error messages  
  103.     public String getCaptcha() {  
  104.         return null;  
  105.     }  
  106.   
  107.     public String getFirstname() {  
  108.         return firstname;  
  109.     }  
  110.   
  111.     public void setFirstname(String firstname) {  
  112.         this.firstname = firstname;  
  113.     }  
  114.   
  115.     public String getLastname() {  
  116.         return lastname;  
  117.     }  
  118.   
  119.     public void setLastname(String lastname) {  
  120.         this.lastname = lastname;  
  121.     }  
  122.   
  123.     public String getUsername() {  
  124.         return username;  
  125.     }  
  126.   
  127.     public void setUsername(String username) {  
  128.         this.username = username;  
  129.     }  
  130.   
  131.     public String getSex() {  
  132.         return sex;  
  133.     }  
  134.   
  135.     public void setSex(String sex) {  
  136.         this.sex = sex;  
  137.     }  
  138.   
  139.     public String getEmail() {  
  140.         return email;  
  141.     }  
  142.   
  143.     public void setEmail(String email) {  
  144.         this.email = email;  
  145.     }  
  146.   
  147.     public String getPassword() {  
  148.         return password;  
  149.     }  
  150.   
  151.     public void setPassword(String password) {  
  152.         this.password = password;  
  153.     }  
  154.   
  155.     public Set<Address> getAddress() {  
  156.         return address;  
  157.     }  
  158.   
  159.     public void setAddress(Set<Address> address) {  
  160.         this.address = address;  
  161.     }  
  162.   
  163.     public Role getRole() {  
  164.         return role;  
  165.     }  
  166.   
  167.     public void setRole(Role role) {  
  168.         this.role = role;  
  169.     }  
  170.   
  171.     public boolean isConfirmed() {  
  172.         return confirmed;  
  173.     }  
  174.   
  175.     public void setConfirmed(boolean confirmed) {  
  176.         this.confirmed = confirmed;  
  177.     }  
  178.   
  179.     public String getConfirmedID() {  
  180.         return confirmedID;  
  181.     }  
  182.   
  183.     public void setConfirmedID(String confirmedID) {  
  184.         this.confirmedID = confirmedID;  
  185.     }  
  186.   
  187.     public Date getCreate() {  
  188.         return create;  
  189.     }  
  190.   
  191.     public Date getUpdate() {  
  192.         return update;  
  193.     }  
  194.   
  195.     @PrePersist  
  196.     protected void onCreate() {  
  197.         this.create = this.update = new Date();  
  198.     }  
  199.   
  200.     @PreUpdate  
  201.     protected void onUpdate() {  
  202.         this.update = new Date();  
  203.     }  
  204.   
  205.     @Override  
  206.     public int hashCode() {  
  207.         int ret = HashCodeUtil.SEED;  
  208.         ret = HashCodeUtil.hash(ret, id);  
  209.         ret = HashCodeUtil.hash(ret, firstname);  
  210.         ret = HashCodeUtil.hash(ret, lastname);  
  211.         ret = HashCodeUtil.hash(ret, sex);  
  212.         ret = HashCodeUtil.hash(ret, email);  
  213.         ret = HashCodeUtil.hash(ret, password);  
  214.         ret = HashCodeUtil.hash(ret, address);  
  215.         ret = HashCodeUtil.hash(ret, role);  
  216.   
  217.         return ret;  
  218.     }  
  219.   
  220.     @Override  
  221.     public boolean equals(Object obj) {  
  222.         if (obj == null) {  
  223.             return false;  
  224.         }  
  225.   
  226.         if (this == obj) {  
  227.             return true;  
  228.         }  
  229.   
  230.         if (!(obj instanceof User)) {  
  231.             return false;  
  232.         }  
  233.   
  234.         User u = (User) obj;  
  235.   
  236.         if (this.id == u.id) {  
  237.             return true;  
  238.         } else {  
  239.             return false;  
  240.         }  
  241.     }  
  242.   
  243.     @Override  
  244.     public String toString() {  
  245.         StringBuilder sb = new StringBuilder();  
  246.   
  247.         sb.append("\nID: ");  
  248.         sb.append(id);  
  249.   
  250.         sb.append("\nFirstname: ");  
  251.         sb.append(firstname);  
  252.   
  253.         sb.append("\nLastname: ");  
  254.         sb.append(lastname);  
  255.   
  256.         sb.append("\nSex: ");  
  257.         sb.append(sex);  
  258.   
  259.         sb.append("\nEmail: ");  
  260.         sb.append(email);  
  261.   
  262.         sb.append("\nAddress: ");  
  263.         sb.append(address.toString());  
  264.   
  265.         sb.append("\nRole: ");  
  266.         sb.append(role.toString());  
  267.   
  268.         return sb.toString();  
  269.     }  
  270. }  

UserList:该类是普通类(不是实体类@Entity),不在数据库中创建相应表格,仅仅在程序执行过程中使用,用于保存多个用户。

  1. package com.haibin.rest.domain;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. public class UserList {  
  7.     private List<User> users = new ArrayList<User>();  
  8.   
  9.     public List<User> getUsers() {  
  10.         return users;  
  11.     }  
  12.   
  13.     public void setUsers(List<User> users) {  
  14.         users.clear();  
  15.         users.addAll(users);  
  16.     }  
  17.   
  18.     public void addUsers(List<User> users) {  
  19.         this.users.addAll(users);  
  20.     }  
  21.   
  22.     public void addUser(User user) {  
  23.         users.add(user);  
  24.     }  
  25. }  

Role:该实体类用于表示用户的角色,管理员或普通用户,后面谈到的Spring Security时再做介绍。

  1. package com.haibin.rest.domain;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.GenerationType;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.OneToOne;  
  11. import javax.persistence.Table;  
  12.   
  13. @Entity  
  14. @Table(name = "ROLE")  
  15. public class Role implements Serializable {  
  16.   
  17.     private static final long serialVersionUID = -3559053024369633882L;  
  18.   
  19.     @Id  
  20.     @GeneratedValue(strategy = GenerationType.AUTO)  
  21.     @Column(name = "ROLE_ID")  
  22.     private Long id;  
  23.   
  24.     @OneToOne  
  25.     private User user;  
  26.   
  27.     @Column(name = "ROLE_ROLE")  
  28.     private Integer role;  
  29.   
  30.     public Role() {  
  31.   
  32.     }  
  33.   
  34.     public Long getId() {  
  35.         return id;  
  36.     }  
  37.   
  38.     public void setId(Long id) {  
  39.         this.id = id;  
  40.     }  
  41.   
  42.     public User getUser() {  
  43.         return user;  
  44.     }  
  45.   
  46.     public void setUser(User user) {  
  47.         this.user = user;  
  48.     }  
  49.   
  50.     public Integer getRole() {  
  51.         return role;  
  52.     }  
  53.   
  54.     public void setRole(Integer role) {  
  55.         this.role = role;  
  56.     }  
  57. }  

Address:该实体类用户存放用户的地址信息。

  1. package com.haibin.rest.domain;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.GenerationType;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.Table;  
  11.   
  12. import com.haibin.rest.utils.HashCodeUtil;  
  13.   
  14. @Entity  
  15. @Table(name = "ADDRESS")  
  16. public class Address implements Serializable {  
  17.   
  18.     private static final long serialVersionUID = 1358043349847785726L;  
  19.   
  20.     @Id  
  21.     @GeneratedValue(strategy = GenerationType.AUTO)  
  22.     @Column(name = "ADDRESS_ID")  
  23.     private long id;  
  24.   
  25.     @Column(name = "ADDRESS_COUNTRY")  
  26.     private String country;  
  27.   
  28.     @Column(name = "ADDRESS_STATE")  
  29.     private String state;  
  30.   
  31.     @Column(name = "ADDRESS_CITY")  
  32.     private String city;  
  33.   
  34.     @Column(name = "ADDRESS_STREET")  
  35.     private String street;  
  36.   
  37.     @Column(name = "ADDRESS_ZIPCODE")  
  38.     private String zipCode;  
  39.   
  40.     public Address() {  
  41.   
  42.     }  
  43.   
  44.     public Address(String country, String state, String city, String street,  
  45.             String zipCode) {  
  46.         super();  
  47.         this.country = country;  
  48.         this.state = state;  
  49.         this.city = city;  
  50.         this.street = street;  
  51.         this.zipCode = zipCode;  
  52.     }  
  53.   
  54.     public long getId() {  
  55.         return id;  
  56.     }  
  57.   
  58.     public void setId(long id) {  
  59.         this.id = id;  
  60.     }  
  61.   
  62.     public String getCountry() {  
  63.         return country;  
  64.     }  
  65.   
  66.     public void setCountry(String country) {  
  67.         this.country = country;  
  68.     }  
  69.   
  70.     public String getState() {  
  71.         return state;  
  72.     }  
  73.   
  74.     public void setState(String state) {  
  75.         this.state = state;  
  76.     }  
  77.   
  78.     public String getCity() {  
  79.         return city;  
  80.     }  
  81.   
  82.     public void setCity(String city) {  
  83.         this.city = city;  
  84.     }  
  85.   
  86.     public String getStreet() {  
  87.         return street;  
  88.     }  
  89.   
  90.     public void setStreet(String street) {  
  91.         this.street = street;  
  92.     }  
  93.   
  94.     public String getZipCode() {  
  95.         return zipCode;  
  96.     }  
  97.   
  98.     public void setZipCode(String zipCode) {  
  99.         this.zipCode = zipCode;  
  100.     }  
  101.   
  102.     @Override  
  103.     public int hashCode() {  
  104.         int ret = HashCodeUtil.SEED;  
  105.         ret = HashCodeUtil.hash(ret, id);  
  106.         ret = HashCodeUtil.hash(ret, country);  
  107.         ret = HashCodeUtil.hash(ret, state);  
  108.         ret = HashCodeUtil.hash(ret, city);  
  109.         ret = HashCodeUtil.hash(ret, street);  
  110.         ret = HashCodeUtil.hash(ret, zipCode);  
  111.   
  112.         return ret;  
  113.     }  
  114.   
  115.     @Override  
  116.     public boolean equals(Object obj) {  
  117.         if (obj == null) {  
  118.             return false;  
  119.         }  
  120.         if (this == obj) {  
  121.             return true;  
  122.         }  
  123.         if (!(obj instanceof Address)) {  
  124.             return false;  
  125.         }  
  126.   
  127.         Address a = (Address) obj;  
  128.         return this.id == a.id && this.country == a.country  
  129.                 && this.state == a.state && this.city == a.city  
  130.                 && this.zipCode == a.zipCode;  
  131.     }  
  132.   
  133.     @Override  
  134.     public String toString() {  
  135.         StringBuilder sb = new StringBuilder();  
  136.   
  137.         sb.append("\nCountry: ");  
  138.         sb.append(country);  
  139.   
  140.         sb.append("\tState: ");  
  141.         sb.append(state);  
  142.   
  143.         sb.append("\tCity: ");  
  144.         sb.append(city);  
  145.   
  146.         sb.append("\tStreet: ");  
  147.         sb.append(street);  
  148.   
  149.         sb.append("\tZipcode: ");  
  150.         sb.append(zipCode);  
  151.   
  152.         return sb.toString();  
  153.     }  
  154. }  

注意:实体类(User、Role、Address)使用了Bean风格的定义,有构造函数、get方法和set方法。


2. Controller:


注册登录系统是基于Spring MVC、Annotation开发的,为了文章篇幅不至于太过于冗长,本文就不再对Spring MVC和Annotation进行深入介绍,请谅解。控制器实体类采用了Restful风格,类定义了CRUD四种操作分别对应creat、get、update和delete四个方法,用于创建用户,读取用户信息、更新用户信息和删除用户。

控制器类都使用了@Controller注释标注。

UserController:该类用于控制用户的创建、用户信息的读取、用户信息的更新及删除用户。

@Controller说明UserController是控制器类;@RequestMapping("/users")用于说明发送到http://domain/users的请求都由控制器UserController进行处理。

注入方式定义了userService成员,userService封装了数据库的各种操作。

@RequestMapping(value = "/records", method = RequestMethod.GET):该注释说明发送到http://domain//users/records的get请求都由getUsers方法进行处理。

create:create方法创建用户并将用户信息保存到数据库。值得注意的一点:数据库并不直接保存用户密码明文信息,而是保存了密码的MD5值,增强了系统的安全性。

  1. package com.haibin.rest.controller;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.security.crypto.password.StandardPasswordEncoder;  
  7. import org.springframework.stereotype.Controller;  
  8. import org.springframework.web.bind.annotation.RequestBody;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.RequestParam;  
  12. import org.springframework.web.bind.annotation.ResponseBody;  
  13.   
  14. import com.haibin.rest.domain.Role;  
  15. import com.haibin.rest.domain.User;  
  16. import com.haibin.rest.domain.UserList;  
  17. import com.haibin.rest.service.UserService;  
  18.   
  19. @Controller  
  20. @RequestMapping("/users")  
  21. public class UserController {  
  22.     private static final Logger logger = LoggerFactory  
  23.             .getLogger(UserController.class);  
  24.   
  25.     @Autowired  
  26.     private UserService userService;  
  27.   
  28.     @RequestMapping  
  29.     public String getUsersPage() {  
  30.         return "users";  
  31.     }  
  32.   
  33.     //  ResponseBody  
  34.     @RequestMapping(value = "/records", method = RequestMethod.GET)  
  35.     @ResponseBody  
  36.     public UserList getUsers() {  
  37.         return userService.readAll();  
  38.     }  
  39.   
  40.     @RequestMapping(value = "/get", method = RequestMethod.GET)  
  41.     @ResponseBody  
  42.     public User get(@RequestBody User user) {  
  43.         return userService.read(user);  
  44.     }  
  45.   
  46.     @RequestMapping(value = "/create", method = RequestMethod.PUT)  
  47.     public String create(@RequestParam String firstname,  
  48.             @RequestParam String lastname, @RequestParam String sex,  
  49.             @RequestParam String email, @RequestParam String password,  
  50.             @RequestParam Integer role) {  
  51.         Role newRole = new Role();  
  52.         newRole.setRole(role);  
  53.   
  54.         User newUser = new User();  
  55.         newUser.setFirstname(firstname);  
  56.         newUser.setLastname(lastname);  
  57.         newUser.setSex(sex);  
  58.         newUser.setEmail(email);  
  59.         newUser.setRole(newRole);  
  60.   
  61.         StandardPasswordEncoder encoder = new StandardPasswordEncoder();  
  62.         String hashPass = encoder.encode(password);  
  63.         logger.debug("{}: hash password is {}"this.getClass(), hashPass);  
  64.   
  65.         newUser.setPassword(password);  
  66.   
  67.         userService.create(newUser);  
  68.   
  69.         return "redirect:registerSuccess.htm";  
  70.     }  
  71.   
  72.     @RequestMapping(value = "/update", method = RequestMethod.POST)  
  73.     @ResponseBody  
  74.     public User update(@RequestParam String firstname,  
  75.             @RequestParam String lastname, @RequestParam String sex,  
  76.             @RequestParam String email, @RequestParam Integer role) {  
  77.         Role existingRole = new Role();  
  78.         existingRole.setRole(role);  
  79.   
  80.         User existingUser = new User();  
  81.         existingUser.setFirstname(firstname);  
  82.         existingUser.setLastname(lastname);  
  83.         existingUser.setSex(sex);  
  84.         existingUser.setEmail(email);  
  85.         existingUser.setRole(existingRole);  
  86.   
  87.         userService.update(existingUser);  
  88.         return existingUser;  
  89.     }  
  90.   
  91.     @RequestMapping(value = "/delete", method = RequestMethod.DELETE)  
  92.     @ResponseBody  
  93.     public Boolean delete(@RequestParam String username) {  
  94.         User user = new User();  
  95.         user.setUsername(username);  
  96.         return userService.delete(user);  
  97.     }  
  98.       
  99. }  

RegisterController

MA_USER、MA_RECAPTCHA_HMTL:用作model属性的key,将信息从控制器传送到视图。

userRepository:对数据表USER进行CRUD操作的对象。

reCaptcha:防止机器注册的captcha对象。

userValidator:对用户从视图输入的信息进行验证的对象。

mailSender:用于向注册邮箱发送确认连接的发送者对象。

message:邮件对象。

authenticationManager:认证管理器对象。

register():当用户对http://domain/register发送GET请求时,执行register方法,register方法首先创建user、role对象,并进行初始化,user和role对象的其他信息会在用户提交注册表单时获得;生成新的captcha;将user和captcha html对象放进model内,通过return操作传送到register.jsp视图。

registerProcessor():当用户正确填写完注册表单,点击提交按钮时registerProcessor方法被调用。registerProcessor方法首先验证user对象各成员数据是否合法,不合法提示错误信息;检验captcha是否一致,不一致发送新的captcha并重新进入register.jsp页面;产生并设置确认id;产生并设置密码MD5值;构造确认邮件并发送邮件,转向registerSuccess.jsp页面,页面提示用户登录邮箱进行确认,用户只有访问了确认链接后才可登录系统。注意:如果系统允许用户注册后马上自动登录,可以使用注释掉的doAutoLogin()函数并注释后面的构造并发送邮件的代码,修改return值来实现该功能。

确认register():当用户进行确认时,确认register方法被调用,函数通过确认连接中的确认id查找对应用户,查找成功后设置confirmed成员为true,提示注册成功信息并提示登录。查找用户失败,给出失败信息。

doAutoLogin():实现注册完成后自动登录的功能。

  1. package com.haibin.rest.controller;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6.   
  7. import net.tanesha.recaptcha.ReCaptcha;  
  8. import net.tanesha.recaptcha.ReCaptchaResponse;  
  9.   
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.beans.factory.annotation.Autowired;  
  13. import org.springframework.beans.factory.annotation.Qualifier;  
  14. import org.springframework.mail.MailSender;  
  15. import org.springframework.mail.SimpleMailMessage;  
  16. import org.springframework.security.authentication.AuthenticationManager;  
  17. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;  
  18. import org.springframework.security.core.Authentication;  
  19. import org.springframework.security.core.context.SecurityContextHolder;  
  20. import org.springframework.security.crypto.password.StandardPasswordEncoder;  
  21. import org.springframework.security.web.authentication.WebAuthenticationDetails;  
  22. import org.springframework.stereotype.Controller;  
  23. import org.springframework.ui.Model;  
  24. import org.springframework.validation.BindingResult;  
  25. import org.springframework.web.bind.annotation.ModelAttribute;  
  26. import org.springframework.web.bind.annotation.RequestMapping;  
  27. import org.springframework.web.bind.annotation.RequestMethod;  
  28. import org.springframework.web.bind.annotation.RequestParam;  
  29.   
  30. import com.haibin.rest.domain.Role;  
  31. import com.haibin.rest.domain.User;  
  32. import com.haibin.rest.repository.UserRepository;  
  33. import com.haibin.rest.validator.UserValidator;  
  34.   
  35. @Controller  
  36. public class RegisterController {  
  37.     private static final Logger logger = LoggerFactory  
  38.             .getLogger(RegisterController.class);  
  39.     private static final String MA_USER = "user";  
  40.     private static final String MA_RECAPTCHA_HTML = "reCaptchaHtml";  
  41.   
  42.     @Autowired  
  43.     private UserRepository userRepository;  
  44.   
  45.     @Autowired  
  46.     private ReCaptcha reCaptcha;  
  47.   
  48.     @Autowired  
  49.     private UserValidator userValidator;  
  50.   
  51.     @Autowired  
  52.     private MailSender mailSender;  
  53.   
  54.     @Autowired  
  55.     private SimpleMailMessage message;  
  56.   
  57.     @Autowired  
  58.     @Qualifier("org.springframework.security.authenticationManager")  
  59.     private AuthenticationManager authenticationManager;  
  60.   
  61.     @RequestMapping(value = "/register", method = RequestMethod.GET)  
  62.     public String register(Model model) {  
  63.   
  64.         User user = new User();  
  65.         Role role = new Role();  
  66.         user.setRole(role);  
  67.         role.setUser(user);  
  68.   
  69.         model.addAttribute(MA_USER, user);  
  70.   
  71.         String html = reCaptcha.createRecaptchaHtml(nullnull);  
  72.         model.addAttribute(MA_RECAPTCHA_HTML, html);  
  73.   
  74.         return "register";  
  75.     }  
  76.   
  77.     @RequestMapping(value = "/register", method = RequestMethod.POST)  
  78.     public String registerProcessor(HttpServletRequest request,  
  79.             @RequestParam("recaptcha_challenge_field") String challenge,  
  80.             @RequestParam("recaptcha_response_field") String response,  
  81.             @ModelAttribute(MA_USER) User user, BindingResult result,  
  82.             Model model) throws IOException {  
  83.   
  84.         logger.info("{}: challenge = {}"this.getClass(), challenge);  
  85.         logger.info("{}: response = {}"this.getClass(), response);  
  86.   
  87.         userValidator.validate(user, result);  
  88.   
  89.         ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(  
  90.                 request.getRemoteAddr(), challenge, response);  
  91.         if (!reCaptchaResponse.isValid()) {  
  92.             result.rejectValue("captcha""captcha.invalid",  
  93.                     "Please try again. Hover over the red buttons for additional options.");  
  94.         }  
  95.   
  96.         String html = reCaptcha.createRecaptchaHtml(nullnull);  
  97.         model.addAttribute(MA_RECAPTCHA_HTML, html);  
  98.   
  99.         if (result.hasErrors()) {  
  100.             return "register";  
  101.         }  
  102.   
  103.         // Generate a unique confirmation ID for this user  
  104.         user.setConfirmedID(java.util.UUID.randomUUID().toString());  
  105.   
  106.         String password = user.getPassword();  
  107.   
  108.         // Store the hash password of plain text password into database.  
  109.         StandardPasswordEncoder encoder = new StandardPasswordEncoder();  
  110.         String hashPass = encoder.encode(password);  
  111.         logger.info("{}: hashed password: {}"this.getClass(), hashPass);  
  112.   
  113.         user.setPassword(hashPass);  
  114.   
  115.         userRepository.save(user);  
  116.   
  117.         // Automatic login after successful registration.  
  118.         // doAutoLogin(user.getUsername(), password, request);  
  119.   
  120.         // Send confirmation email to requestor  
  121.         StringBuilder sb = new StringBuilder();  
  122.         sb.append("http://localhost:8080/rest/confirm?id=");  
  123.         sb.append(user.getConfirmedID());  
  124.   
  125.         sendConfirmEmail(user.getEmail(), "Last Step to complete registration",  
  126.                 sb.toString());  
  127.   
  128.         return "redirect:/registerSuccess.html";  
  129.     }  
  130.   
  131.     @RequestMapping(value = "/registerSuccess.html", method = RequestMethod.GET)  
  132.     public String registerSuccessView() {  
  133.         return "registerSuccess";  
  134.     }  
  135.   
  136.     @RequestMapping(value = "/confirm", method = RequestMethod.GET)  
  137.     public String register(@RequestParam("id") String id) {  
  138.         User user = userRepository.findByConfirmedID(id);  
  139.         if (user == null) {  
  140.             return "no user corresponds to this confirm link, please register";  
  141.         }  
  142.         if (user.isConfirmed()) {  
  143.             return "user has confirmed";  
  144.         }  
  145.   
  146.         user.setConfirmed(true);  
  147.         userRepository.save(user);  
  148.   
  149.         return "redirect:/confirmSuccess.html";  
  150.     }  
  151.   
  152.     @RequestMapping(value = "/confirmSuccess.html", method = RequestMethod.GET)  
  153.     public String confirmSuccessView() {  
  154.         return "confirmSuccess";  
  155.     }  
  156.   
  157.     private void sendConfirmEmail(String to, String subject, String confirmLink) {  
  158.         message.setTo(to);  
  159.         message.setSubject(subject);  
  160.   
  161.         message.setText(confirmLink);  
  162.   
  163.         mailSender.send(message);  
  164.     }  
  165.   
  166.     // Notice: make sure the password input of doAutoLogin() is plain text  
  167.     @SuppressWarnings("unused")  
  168.     private void doAutoLogin(String username, String password,  
  169.             HttpServletRequest request) {  
  170.         try {  
  171.             // Must be called from request filtered by Spring Security,  
  172.             // otherwise SecurityContextHolder is not updated  
  173.             UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(  
  174.                     username, password);  
  175.   
  176.             // generate session if one doesn't exist  
  177.             request.getSession();  
  178.   
  179.             token.setDetails(new WebAuthenticationDetails(request));  
  180.             Authentication authentication = this.authenticationManager  
  181.                     .authenticate(token);  
  182.   
  183.             SecurityContextHolder.getContext()  
  184.                     .setAuthentication(authentication);  
  185.   
  186.         } catch (Exception e) {  
  187.             SecurityContextHolder.getContext().setAuthentication(null);  
  188.             logger.error("{}: Failure in doAutoLogin!!!"this.getClass(), e);  
  189.         }  
  190.     }  
  191. }  

MediatorController:该控制器主要起到了跳转功能,完成了apache中.htaccess rewrite的部分工作。如:当用户访问http://domain/home时,会自动跳转到http://domain/home.jsp。
LoginController:该控制器实现了登录功能,比较简单就不详细介绍。

3. Repository ( Spring Data JPA ):

之前的一篇文章介绍的是Spring + JPA 2 + Mysql,如果忽略本文使用的其他技术,那么这篇文章介绍的是 Spring + Spring Data JPA + Mysql。Spring Data JPA的出现进一步简化了数据库访问,作者再次偷懒,不展开介绍Spring Data JPA。如果想了解JPA2 和 Spring Data JPA两种代码风格的区别可以下载查看作者上篇Spring和本篇文章中提供的源码链接,或者网上搜索相关代码。
Spring Data JPA提供了访问数据库的几种接口,本文使用的到的是CrudRepository接口,接口中提供了findAll(), save()等默认方法,用户只需定义对应实体类的接口继承CrudRepository即可使用。如果用户使用接口中未提供的方法,比如用户想通过username获得用户信息,可以按照规范提供相应方法的接口即可,如 User findByUsername(String username),注意方法的名字由findBy + 成员名(首字母大写)构成,方法的参数类型和参数名必须和User类定义中的一致。按照规范给出方法签名后,Spring Data JPA会自动完成所希望的功能,只管调用即可,比如UserService中使用UserRepository对数据库进行操作。

4. Service:

UserService:对User的各种操作进行了封装。

  1. package com.haibin.rest.service;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.slf4j.Logger;  
  7. import org.slf4j.LoggerFactory;  
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.stereotype.Service;  
  10. import org.springframework.transaction.annotation.Transactional;  
  11.   
  12. import com.haibin.rest.domain.Role;  
  13. import com.haibin.rest.domain.User;  
  14. import com.haibin.rest.domain.UserList;  
  15. import com.haibin.rest.repository.RoleRepository;  
  16. import com.haibin.rest.repository.UserRepository;  
  17.   
  18. @Service  
  19. @Transactional  
  20. public class UserService {  
  21.   
  22.     private static final Logger logger = LoggerFactory  
  23.             .getLogger(UserService.class);  
  24.   
  25.     @Autowired  
  26.     private UserRepository userRepository;  
  27.   
  28.     @Autowired  
  29.     private RoleRepository roleRepository;  
  30.   
  31.     public User create(User user) {  
  32.         User existingUser = userRepository.findByUsername(user.getUsername());  
  33.         if (existingUser != null) {  
  34.             logger.debug("{}: user has existed"this.getClass());  
  35.             return null;  
  36.         }  
  37.   
  38.         user.getRole().setUser(user);  
  39.   
  40.         User saved = userRepository.save(user);  
  41.         if (saved == null) {  
  42.             logger.debug("{}: fail to create"this.getClass());  
  43.             return null;  
  44.         }  
  45.   
  46.         return saved;  
  47.     }  
  48.   
  49.     public User read(User user) {  
  50.         return userRepository.findByUsername(user.getUsername());  
  51.     }  
  52.   
  53.     public User update(User user) {  
  54.         User existingUser = userRepository.findByUsername(user.getUsername());  
  55.         if (existingUser == null) {  
  56.             logger.debug("{}:user doesn't exist"this.getClass());  
  57.             return null;  
  58.         }  
  59.   
  60.         // Only firstname, lastname, and role fields are updatable  
  61.         existingUser.setFirstname(user.getFirstname());  
  62.         existingUser.setLastname(user.getLastname());  
  63.         existingUser.getRole().setRole(user.getRole().getRole());  
  64.   
  65.         Role roleSaved = roleRepository.save(existingUser.getRole());  
  66.         if (roleSaved == null) {  
  67.             logger.debug("{}:fail to update role"this.getClass());  
  68.             return null;  
  69.         }  
  70.   
  71.         User saved = userRepository.save(existingUser);  
  72.         if (saved == null) {  
  73.             logger.debug("{}:fail to update user"this.getClass());  
  74.             return null;  
  75.         }  
  76.   
  77.         return saved;  
  78.     }  
  79.   
  80.     public boolean delete(User user) {  
  81.         User existingUser = userRepository.findByUsername(user.getUsername());  
  82.         if (existingUser == null) {  
  83.             logger.debug("{}:user doesn't exist"this.getClass());  
  84.             return false;  
  85.         }  
  86.   
  87.         userRepository.delete(existingUser);  
  88.   
  89.         return true;  
  90.     }  
  91.   
  92.     public UserList readAll() {  
  93.         UserList userList = new UserList();  
  94.         List<User> list = new ArrayList<User>();  
  95.         Iterable<User> users = userRepository.findAll();  
  96.         for (User user : users) {  
  97.             list.add(user);  
  98.         }  
  99.   
  100.         userList.setUsers(list);  
  101.   
  102.         return userList;  
  103.     }  
  104. }  

CustomUserDetailsService:使用Spring Security需要实现的服务。

  1. package com.haibin.rest.service;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.List;  
  6.   
  7. import org.slf4j.Logger;  
  8. import org.slf4j.LoggerFactory;  
  9. import org.springframework.beans.factory.annotation.Autowired;  
  10. import org.springframework.security.core.GrantedAuthority;  
  11. import org.springframework.security.core.authority.SimpleGrantedAuthority;  
  12. import org.springframework.security.core.userdetails.User;  
  13. import org.springframework.security.core.userdetails.UserDetails;  
  14. import org.springframework.security.core.userdetails.UserDetailsService;  
  15. import org.springframework.security.core.userdetails.UsernameNotFoundException;  
  16. import org.springframework.stereotype.Service;  
  17. import org.springframework.transaction.annotation.Transactional;  
  18.   
  19. import com.haibin.rest.repository.UserRepository;  
  20.   
  21. @Service  
  22. @Transactional(readOnly = true)  
  23. public class CustomUserDetailsService implements UserDetailsService {  
  24.   
  25.     private static final Logger logger = LoggerFactory  
  26.             .getLogger(CustomUserDetailsService.class);  
  27.   
  28.     @Autowired  
  29.     private UserRepository userRepository;  
  30.   
  31.     /** 
  32.      * Returns a populated {@link UserDetails} object. The useremail is first 
  33.      * retrieved from the database and then mapped to a {@link UserDetails} 
  34.      * object. 
  35.      */  
  36.     @Override  
  37.     public UserDetails loadUserByUsername(String username)  
  38.             throws UsernameNotFoundException {  
  39.   
  40.         // Search database for a user that matches the specified username  
  41.         com.haibin.rest.domain.User user = userRepository  
  42.                 .findByUsername(username);  
  43.   
  44.         boolean enabled = true;  
  45.         boolean accountNonExpired = true;  
  46.         boolean credentialsNonExpired = true;  
  47.         boolean accountNonLocked = true;  
  48.   
  49.         if (user == null) {  
  50.             logger.info("{}: no such user exists"this.getClass());  
  51.             throw new UsernameNotFoundException(username);  
  52.         }  
  53.         else if(user.isConfirmed() == false) {  
  54.             logger.info("{}: user doesn't confirm"this.getClass());  
  55.             throw new UsernameNotFoundException(username);  
  56.         }  
  57.   
  58.         // Populate the Spring User object with details from database user.  
  59.         return new User(user.getUsername(), user.getPassword().toLowerCase(),  
  60.                 enabled, accountNonExpired, credentialsNonExpired,  
  61.                 accountNonLocked, getAuthorities(user.getRole().getRole()));  
  62.   
  63.     }  
  64.   
  65.     /** 
  66.      * Retrieves a collection of {@link GrantedAuthority} based on a numerical 
  67.      * role 
  68.      *  
  69.      * @param role 
  70.      *            the numerical role 
  71.      * @return a collection of {@link GrantedAuthority 
  72.  
  73.      */  
  74.     public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {  
  75.         List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));  
  76.         return authList;  
  77.     }  
  78.   
  79.     /** 
  80.      * Converts a numerical role to an equivalent list of roles 
  81.      *  
  82.      * @param role 
  83.      *            the numerical role 
  84.      * @return list of roles as as a list of {@link String} 
  85.      */  
  86.     public List<String> getRoles(Integer role) {  
  87.         List<String> roles = new ArrayList<String>();  
  88.   
  89.         if (role.intValue() == 1) {  
  90.             roles.add("ROLE_USER");  
  91.             roles.add("ROLE_ADMIN");  
  92.   
  93.         } else if (role.intValue() == 2) {  
  94.             roles.add("ROLE_USER");  
  95.         }  
  96.   
  97.         return roles;  
  98.     }  
  99.   
  100.     /** 
  101.      * Wraps {@link String} roles to {@link SimpleGrantedAuthority} objects 
  102.      *  
  103.      * @param roles 
  104.      *            {@link String} of roles 
  105.      * @return list of granted authorities 
  106.      */  
  107.     public static List<GrantedAuthority> getGrantedAuthorities(  
  108.             List<String> roles) {  
  109.         List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();  
  110.         for (String role : roles) {  
  111.             authorities.add(new SimpleGrantedAuthority(role));  
  112.         }  
  113.         return authorities;  
  114.     }  
  115. }  

5. Validator:

UserValidator:对用户提供的信息进行验证,没有通过验证的给出出错信息,出错信息定义在src/main/resources/messages.properties文件内。


6. 配置:

web.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  5.   
  6.     <!-- Enables support for DELETE and PUT request methods with web browser   
  7.         clients -->  
  8.     <filter>  
  9.         <filter-name>hiddenHttpMethodFilter</filter-name>  
  10.         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>  
  11.     </filter>  
  12.     <filter-mapping>  
  13.         <filter-name>hiddenHttpMethodFilter</filter-name>  
  14.         <url-pattern>/*</url-pattern>  
  15.     </filter-mapping>  
  16.   
  17.   
  18.     <!-- Spring Security -->  
  19.     <filter>  
  20.         <filter-name>springSecurityFilterChain</filter-name>  
  21.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  22.     </filter>  
  23.   
  24.     <filter-mapping>  
  25.         <filter-name>springSecurityFilterChain</filter-name>  
  26.         <url-pattern>/*</url-pattern>  
  27.     </filter-mapping>  
  28.   
  29.   
  30.     <!-- The definition of the Root Spring Container shared by all Servlets   
  31.         and Filters -->  
  32.     <context-param>  
  33.         <param-name>contextConfigLocation</param-name>  
  34.         <param-value>  
  35.             /WEB-INF/spring/spring-security.xml  
  36.             /WEB-INF/spring/root-context.xml  
  37.         </param-value>  
  38.     </context-param>  
  39.   
  40.     <!-- Creates the Spring Container shared by all Servlets and Filters -->  
  41.     <listener>  
  42.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  43.     </listener>  
  44.   
  45.     <!-- Processes application requests -->  
  46.     <servlet>  
  47.         <servlet-name>appServlet</servlet-name>  
  48.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  49.         <init-param>  
  50.             <param-name>contextConfigLocation</param-name>  
  51.             <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>  
  52.         </init-param>  
  53.         <load-on-startup>1</load-on-startup>  
  54.     </servlet>  
  55.   
  56.     <servlet-mapping>  
  57.         <servlet-name>appServlet</servlet-name>  
  58.         <url-pattern>/</url-pattern>  
  59.     </servlet-mapping>  
  60.   
  61.     <!-- Disables Servlet Container welcome file handling. Needed for compatibility   
  62.         with Servlet 3.0 and Tomcat 7.0 -->  
  63.     <welcome-file-list>  
  64.         <welcome-file></welcome-file>  
  65.     </welcome-file-list>  
  66.   
  67. </web-app>  

servlet-context.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans:beans xmlns="http://www.springframework.org/schema/mvc"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd  
  8.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">  
  10.   
  11.     <!-- DispatcherServlet Context: defines this servlet's request-processing   
  12.         infrastructure -->  
  13.   
  14.   
  15.     <!-- Resolves views selected for rendering by @Controllers to .jsp resources   
  16.         in the /WEB-INF/views directory -->  
  17.     <beans:bean  
  18.         class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  19.         p:prefix="/WEB-INF/views/" p:suffix=".jsp" />  
  20.   
  21. </beans:beans>  

root-context.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  6.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  7.     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">  
  8.   
  9.   
  10.     <!-- Activates the Spring infrastructure for various annotations to be detected   
  11.         in bean classes: Spring's @Required and @Autowired, as well as JSR 250's   
  12.         @PostConstruct, @PreDestroy and @Resource (if available), and JPA's @PersistenceContext   
  13.         and @PersistenceUnit (if available). Alternatively, you can choose to activate   
  14.         the individual BeanPostProcessors for those annotations explictly. -->  
  15.     <!-- <context:annotation-config /> -->  
  16.   
  17.   
  18.     <!-- Root Context: defines shared resources visible to all other web components -->  
  19.     <!-- Scans within the base package of the application for @Components to   
  20.         configure as beans, context:component-scan automatically includes context:annotation-config, so context:annotation-config is needless -->  
  21.     <!-- @Controller, @Service, @Repository, @Configuration, etc -->  
  22.     <context:component-scan base-package="com.haibin.rest" />  
  23.   
  24.   
  25.     <!-- Enables the Spring MVC @Controller programming model -->  
  26.     <mvc:annotation-driven />  
  27.   
  28.   
  29.     <!-- Handles HTTP GET requests for /resources/** by efficiently serving   
  30.         up static resources in the ${webappRoot}/resources directory -->  
  31.     <mvc:resources mapping="/resources/**" location="/resources/" />  
  32.       
  33.     <!-- Maps '/' requests to the 'home' view -->  
  34.     <mvc:view-controller path="/" view-name="home"/>  
  35.       
  36.     <mvc:default-servlet-handler/>  
  37.   
  38.   
  39.     <bean id="reCaptcha" class="net.tanesha.recaptcha.ReCaptchaImpl"  
  40.         p:publicKey="***" p:privateKey="***" />  
  41.   
  42.   
  43.     <bean id="messageSource"  
  44.         class="org.springframework.context.support.ResourceBundleMessageSource"  
  45.         p:basename="messages" />  
  46.   
  47.   
  48.     <import resource="spring-data.xml" />  
  49.     <import resource="spring-mail.xml" />  
  50.   
  51. </beans>  

spring-data.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:cache="http://www.springframework.org/schema/cache" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util"  
  6.     xsi:schemaLocation="  
  7.             http://www.springframework.org/schema/beans   
  8.             http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  9.             http://www.springframework.org/schema/cache  
  10.             http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
  11.             http://www.springframework.org/schema/tx   
  12.             http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
  13.             http://www.springframework.org/schema/data/jpa  
  14.             http://www.springframework.org/schema/data/jpa/spring-jpa.xsd  
  15.             http://www.springframework.org/schema/util   
  16.             http://www.springframework.org/schema/util/spring-util-3.1.xsd">  
  17.   
  18.     <!-- Data Source for Development -->  
  19.     <!--    
  20.     <bean id="dataSource"  
  21.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  22.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  23.         <property name="url" value="jdbc:mysql://localhost:3306/hibernate" />  
  24.         <property name="username" value="root" />  
  25.         <property name="password" value="" />  
  26.     </bean>  
  27.     -->  
  28.       
  29.     <!-- Data Source for Production -->  
  30.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  31.         destroy-method="close"  
  32.         p:driverClass="com.mysql.jdbc.Driver"  
  33.         p:jdbcUrl="jdbc:mysql://localhost:3306/hibernate"  
  34.         p:user="root"  
  35.         p:password=""  
  36.         p:initialPoolSize="5"  
  37.         p:maxPoolSize="100"  
  38.         p:minPoolSize="10"  
  39.         p:maxStatements="50"  
  40.         p:acquireIncrement="5"  
  41.         p:idleConnectionTestPeriod="60"  
  42.     />  
  43.   
  44.   
  45.     <!-- JPA Entity Manager Factory -->  
  46.     <bean id="entityManagerFactory"  
  47.         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"  
  48.         p:packagesToScan="com.haibin.rest" p:dataSource-ref="dataSource"  
  49.         p:jpaVendorAdapter-ref="hibernateVendor" p:jpaPropertyMap-ref="jpaPropertyMap" />  
  50.   
  51.     <bean id="hibernateVendor"  
  52.         class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"  
  53.         p:database="MYSQL" p:showSql="true" p:generateDdl="true"  
  54.         p:databasePlatform="org.hibernate.dialect.MySQLDialect" />  
  55.   
  56.     <util:map id="jpaPropertyMap">  
  57.         <entry key="hibernate.hbm2ddl.auto" value="update" />  
  58.         <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />  
  59.   
  60.         <!-- To enable Hibernate's second level cache and query cache settings -->  
  61.         <entry key="hibernate.max_fetch_depth" value="4" />  
  62.         <entry key="hibernate.cache.use_second_level_cache" value="true" />  
  63.         <entry key="hibernate.cache.use_query_cache" value="true" />  
  64.         <!-- NOTE: if using net.sf.ehcache.hibernate.EhCacheRegionFactory for Hibernate 4+, probrems happen -->  
  65.         <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />  
  66.     </util:map>  
  67.   
  68.   
  69.     <!-- EhCache Configuration -->  
  70.     <cache:annotation-driven />  
  71.   
  72.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"  
  73.         p:cacheManager-ref="ehcache" />  
  74.   
  75.     <!-- NOTE: make sure p:share="true", or problems happen -->  
  76.     <bean id="ehcache"  
  77.         class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"  
  78.         p:configLocation="/WEB-INF/classes/ehcache.xml" p:shared="true" />  
  79.   
  80.   
  81.     <!-- Transaction Config -->  
  82.     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"  
  83.         p:entityManagerFactory-ref="entityManagerFactory">  
  84.         <property name="jpaDialect">  
  85.             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />  
  86.         </property>  
  87.     </bean>  
  88.   
  89.   
  90.     <!-- User declarative transaction management -->  
  91.     <tx:annotation-driven transaction-manager="transactionManager" />  
  92.   
  93.   
  94.     <!-- This will ensure that Hibernate or JPA exceptions are automatically   
  95.         translated into Spring's generic DataAccessException hierarchy for those   
  96.         classes annotated with Repository. -->  
  97.     <bean  
  98.         class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />  
  99.   
  100.   
  101.     <!-- Activate Spring Data JPA repository support -->  
  102.     <jpa:repositories base-package="com.haibin.rest.repository" />  
  103.   
  104. </beans>  

ehcache.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"  
  4.     monitoring="autodetect" dynamicConfig="true">  
  5.   
  6.     <diskStore path="java.io.tmpdir" />  
  7.       
  8.     <defaultCache  
  9.         maxEntriesLocalHeap="10000"  
  10.         eternal="false"  
  11.         timeToIdleSeconds="120"  
  12.         timeToLiveSeconds="120"  
  13.         overflowToDisk="true"  
  14.         maxEntriesLocalDisk="10000000"  
  15.         diskPersistent="false"  
  16.         diskExpiryThreadIntervalSeconds="120"  
  17.         memoryStoreEvictionPolicy="LRU"  
  18.     />  
  19.   
  20.     <cache name="org.hibernate.cache.UpdateTimestampsCache"  
  21.         maxElementsInMemory="5000"  
  22.         eternal="true"  
  23.         overflowToDisk="true"   
  24.     />  
  25.       
  26.     <cache name="org.hibernate.cache.StandardQueryCache"  
  27.         maxElementsInMemory="5000"  
  28.         eternal="false"  
  29.         timeToIdleSeconds="120"  
  30.         timeToLiveSeconds="120"  
  31.         overflowToDisk="true"  
  32.         diskPersistent="false"  
  33.         diskExpiryThreadIntervalSeconds="120"  
  34.         memoryStoreEvictionPolicy="LRU"/>  
  35.           
  36.     <cache name="com.haibin.rest.domain.User"   
  37.         maxEntriesLocalHeap="50"  
  38.         eternal="false"   
  39.         timeToIdleSeconds="300"  
  40.         timeToLiveSeconds="600"   
  41.         overflowToDisk="true"   
  42.     />     
  43.   
  44. </ehcache>  

spring-mail.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  5.   
  6.     <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  7.         <property name="host" value="smtp.gmail.com" />  
  8.         <property name="port" value="465" />  
  9.         <property name="username" value="***@gmail.com" />  
  10.         <property name="password" value="***"/>  
  11.         <property name="protocol" value="smtps" />  
  12.   
  13.         <property name="javaMailProperties">  
  14.             <props>  
  15.                 <!-- Use SMTP-AUTH to authenticate to SMTP server -->  
  16.                 <prop key="mail.smtps.auth">true</prop>  
  17.                 <!-- User TLS to encrypt communication with SMTP server -->  
  18.                 <prop key="mail.smtps.starttls.enable">true</prop>  
  19.                 <prop key="mail.debug">true</prop>  
  20.             </props>  
  21.         </property>  
  22.     </bean>  
  23.   
  24.     <bean id="message" class="org.springframework.mail.SimpleMailMessage" />  
  25. </beans>  

spring-security.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"  
  3.     xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  6.         http://www.springframework.org/schema/security   
  7.         http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  8.   
  9.     <http pattern="/resources/**" security="none" />  
  10.   
  11.     <http auto-config="true" use-expressions="true" disable-url-rewriting="true">  
  12.         <intercept-url pattern="/register" access="permitAll" />  
  13.         <intercept-url pattern="/registerSuccess" access="permitAll" />  
  14.         <intercept-url pattern="/confirmSuccess" access="permitAll" />  
  15.   
  16.         <intercept-url pattern="/login" access="permitAll" />  
  17.         <intercept-url pattern="/logout" access="permitAll" />  
  18.         <intercept-url pattern="/denied" access="hasRole('ROLE_USER')" />  
  19.         <intercept-url pattern="/" access="hasRole('ROLE_USER')" />  
  20.         <intercept-url pattern="/user" access="hasRole('ROLE_USER')" />  
  21.         <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />  
  22.         <form-login login-page="/login" authentication-failure-url="/login/failure"  
  23.             default-target-url="/" />  
  24.   
  25.         <access-denied-handler error-page="/denied" />  
  26.   
  27.         <logout invalidate-session="true" logout-success-url="/logout/success"  
  28.             logout-url="/logout" />  
  29.     </http>  
  30.   
  31.     <beans:bean id="encoder"   
  32.         class="org.springframework.security.crypto.password.StandardPasswordEncoder">  
  33.     </beans:bean>  
  34.   
  35.     <!-- Declare an authentication-manager to user a custom userDetailService -->  
  36.     <authentication-manager>  
  37.         <authentication-provider user-service-ref="customUserDetailsService">  
  38.             <password-encoder ref="encoder" />  
  39.         </authentication-provider>  
  40.     </authentication-manager>  
  41.   
  42. </beans:beans>  

考虑到文章篇幅,视图相关的内容就不在此叙述了,感兴趣的读者可以下载源码,源码连接: 源码
尝试运行源码需要下列步骤:
1. 下载Eclipse 4 EE
2. 安装maven wtp plugin
3. import 项目
4. 修改项:
root-context.xml:去官网获取recaptcha pubicKey, privateKey,填充到root-context.xml相应位置
spring-data.xml:修改数据库url,username, password与当前你的数据库匹配
spring-mail.xml:填充你的gmail账号和密码
4. 更新依赖
5. 下载tomcat 7
6 run:)

原文链接:http://blog.csdn.net/haibinzhang/article/details/8178143
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值