Shiro與SpringMVC整合


第一部分 什么是Apache Shiro



1、什么是 apache shiro :


Apache Shiro是一個功能強大且易於使用的Java安全框架,提供了認證,授權,加密,和會話管理

如同 Spring security 一樣都是是一個權限安全框架,但是與Spring Security相比,在於他使用了和比較簡潔易懂的認證和授權方式。

 



2、Apache Shiro 的三大核心組件:


1、Subject :當前用戶的操作

2、SecurityManager:用於管理所有的Subject

3、Realms:用於進行權限信息的驗證


Subject:即當前用戶,在權限管理的應用程序里往往需要知道誰能夠操作什么,誰擁 有操作該程序的權利,shiro中則需要通過Subject來提供基礎的當前用戶信息,Subject 不僅僅代表某個用戶,也可以是第三方進程、后台帳戶(Daemon Account)或其他類似事物。

SecurityManager:即所有Subject的管理者,這是Shiro框架的核心組件,可以把他看做是一個Shiro框架的全局管理組件,用於調度各種Shiro框架的服務。

Realms:Realms則是用戶的信息認證器和用戶的權限人證器,我們需要自己來實現Realms來自定義的管理我們自己系統內部的權限規則。

 



3、Authentication 和 Authorization


在shiro的用戶權限認證過程中其通過兩個方法來實現:

1、Authentication:是驗證用戶身份的過程。

2、Authorization:是授權訪問控制,用於對用戶進行的操作進行人證授權,證明該用戶是否允許進行當前操作,如訪問某個鏈接,某個資源文件等。




4、其他組件:


除了以上幾個組件外,Shiro還有幾個其他組件:

1、SessionManager :Shiro為任何應用提供了一個會話編程范式。

2、CacheManager :對Shiro的其他組件提供緩存支持。 

 




5、Shiro 完整架構圖: 



圖片轉自:http://kdboy.iteye.com/blog/1154644


第二部分 Apache Shiro 整合Spring的Web程序構建


1、准備工具:


持久層框架:Hibernate4  這邊我使用了Hibernate來對數據持久層進行操作

控制顯示層框架:SpringMVC 這邊我使用了SpringMVC實際開發中也可以是其他框架

數據庫:MySql

准備好所需要的jar放到項目中。

 


2、創建數據庫:



首先需要四張表,分別為 user(用戶)、role(角色)、permission(權限)、userRole(用戶角色關系表)

這邊分別創建四張表的實體類,通過Hiberante的hibernate.hbm2ddl.auto屬性的update 來自動生成數據表結構。

用戶表:

 1 package com.ssh.entity;
 2 
 3 import java.util.Date;
 4 import java.util.List;
 5 
 6 import javax.persistence.CascadeType;
 7 import javax.persistence.Entity;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.GenerationType;
10 import javax.persistence.Id;
11 import javax.persistence.OneToMany;
12 import javax.persistence.Table;
13 
14 @Table(name="t_user")
15 @Entity
16 public class User {
17     
18     @Id
19     @GeneratedValue(strategy=GenerationType.AUTO)
20     Integer id;
21     
22     String username;
23     String password;
24     Integer isDelete;
25     Date createDate;
26     @OneToMany(mappedBy="user",cascade=CascadeType.ALL)
27     List<UserRole> userRoles;
28     public Integer getId() {
29         return id;
30     }
31     public void setId(Integer id) {
32         this.id = id;
33     }
34     public String getUsername() {
35         return username;
36     }
37     public void setUsername(String username) {
38         this.username = username;
39     }
40     public String getPassword() {
41         return password;
42     }
43     public void setPassword(String password) {
44         this.password = password;
45     }
46     public Integer getIsDelete() {
47         return isDelete;
48     }
49     public void setIsDelete(Integer isDelete) {
50         this.isDelete = isDelete;
51     }
52     public Date getCreateDate() {
53         return createDate;
54     }
55     public void setCreateDate(Date createDate) {
56         this.createDate = createDate;
57     }
58     public List<UserRole> getUserRoles() {
59         return userRoles;
60     }
61     public void setUserRoles(List<UserRole> userRoles) {
62         this.userRoles = userRoles;
63     } 
64     
65     
66 }

 

角色表:

 1 package com.ssh.entity;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.GeneratedValue;
 5 import javax.persistence.GenerationType;
 6 import javax.persistence.Id;
 7 import javax.persistence.Table;
 8 
 9 @Entity  
10 @Table(name = "t_role")  
11 public class Role {
12     
13     @Id
14     @GeneratedValue(strategy = GenerationType.AUTO)
15     Integer id;
16     String name;
17     String description;
18     public Integer getId() {
19         return id;
20     }
21     public void setId(Integer id) {
22         this.id = id;
23     }
24     public String getName() {
25         return name;
26     }
27     public void setName(String name) {
28         this.name = name;
29     }
30     public String getDescription() {
31         return description;
32     }
33     public void setDescription(String description) {
34         this.description = description;
35     }
36     
37 }

 

權限表

 1 package com.ssh.entity;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.GeneratedValue;
 5 import javax.persistence.GenerationType;
 6 import javax.persistence.Id;
 7 import javax.persistence.Table;
 8 
 9 @Entity
10 @Table(name = "t_permission")
11 public class Permission {
12 
13     @Id
14     @GeneratedValue(strategy = GenerationType.AUTO)
15     Integer id;
16     /** token **/
17     String token;
18     /** 資源url **/
19     String url;
20     /** 權限說明 **/
21     String description;
22     /** 所屬角色編號 **/
23     Integer roleId;
24     public Integer getId() {
25         return id;
26     }
27     public void setId(Integer id) {
28         this.id = id;
29     }
30     public String getToken() {
31         return token;
32     }
33     public void setToken(String token) {
34         this.token = token;
35     }
36     public String getUrl() {
37         return url;
38     }
39     public void setUrl(String url) {
40         this.url = url;
41     }
42     public String getDescription() {
43         return description;
44     }
45     public void setDescription(String description) {
46         this.description = description;
47     }
48     public Integer getRoleId() {
49         return roleId;
50     }
51     public void setRoleId(Integer roleId) {
52         this.roleId = roleId;
53     }
54     
55     
56     
57 }

 

用戶角色表:

 1 package com.ssh.entity;
 2 
 3 import javax.persistence.CascadeType;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.GenerationType;
 7 import javax.persistence.Id;
 8 import javax.persistence.JoinColumn;
 9 import javax.persistence.ManyToOne;
10 import javax.persistence.Table;
11 
12 @Entity
13 @Table(name = "t_user_role")
14 public class UserRole {
15     @Id
16     @GeneratedValue(strategy = GenerationType.AUTO)
17     Integer id;
18 
19     @ManyToOne(cascade = CascadeType.ALL)
20     @JoinColumn(name = "userId", unique = true)
21     User user;
22     @ManyToOne
23     @JoinColumn(name = "roleId", unique = true)
24     Role role;
25     public Integer getId() {
26         return id;
27     }
28     public void setId(Integer id) {
29         this.id = id;
30     }
31     public User getUser() {
32         return user;
33     }
34     public void setUser(User user) {
35         this.user = user;
36     }
37     public Role getRole() {
38         return role;
39     }
40     public void setRole(Role role) {
41         this.role = role;
42     }
43     
44 }

 

3、編寫操作用戶業務的Service:

 1 package com.ssh.service;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 
 8 import com.ssh.dao.BaseDao;
 9 import com.ssh.entity.Permission;
10 import com.ssh.entity.Role;
11 import com.ssh.entity.User;
12 import com.ssh.entity.UserRole;
13 
14 public class AccountService {
15      // 公共的數據庫訪問接口  
16     // 這里省略BaseDao dao的編寫  
17     @Autowired  
18     private BaseDao dao;  
19     /**** 
20      * 通過用戶名獲取用戶對象 
21      *  
22      * @param username 
23      * @return 
24      */  
25     public User getUserByUserName(String username){
26         User user = (User) dao.findObjectByHQL("from User where username=?",new Object[]{username});
27         return user;
28     }
29     
30     /***
31      * 通過用戶名獲取權限資源
32      * 
33      * @param username
34      * @return
35      */
36     public List<String> getPermissionsByUserName(String username) {
37         System.out.println("調用");
38         User user = getUserByUserName(username);
39         if(user==null){
40             return null;
41         }
42         List<String> list = new ArrayList<String>();
43         for(UserRole userRole:user.getUserRoles()){
44             Role role = userRole.getRole();
45             List<Permission> permissions = dao.findAllByHQL("FROM Permission WHERE roleId = ?", new Object[] { role.getId() });
46             for (Permission p : permissions) {
47                 list.add(p.getUrl());
48             }
49         }
50         return list;
51     }
52 }

 

BaseDao

 1 package com.ssh.dao;
 2 
 3 import java.util.List;
 4 
 5 public interface BaseDao {
 6 
 7     /***
 8      * 添加
 9      */
10     public void addObject(Object object);
11 
12     /***
13      * 查詢滿足條件 return list
14      */
15     public List findAllByHQL(String hql);
16 
17     /***
18      * 查詢滿足條件的數據
19      * 
20      * @param hql
21      * @param args
22      * @return
23      */
24     public List findAllByHQL(String hql, Object[] args);
25 
26     /***
27      * 查詢滿足條件的對象
28      */
29     public Object findObjectByHQL(String hql);
30 
31     public Object findObjectByHQL(String hql, Object[] args);
32 
33     /***
34      * 查詢滿足條件的對象
35      */
36     public Object findObjectBySQL(String sql);
37 
38     /***
39      * 分頁查詢 return list
40      */
41     public List findPage(String hql, int page, int size);
42 
43     /***
44      * 分頁查詢 帶占位符參數
45      * 
46      * @param hql
47      * @param page
48      * @param size
49      * @param args
50      * @return
51      */
52     public List findPage(String hql, int page, int size, Object[] args);
53 
54     /***
55      * 刪除對象
56      */
57     public void delObject(Object object);
58 
59     /***
60      * 更新對象
61      */
62     public void updateObject(Object object);
63 
64     /***
65      * 批量更新對象 return int
66      */
67     public void updateObjectByHQL(String hql);
68 
69     public void updateObjectByHQL(String hql, Object[] params);
70 
71     /***
72      * 通過sql查詢所有
73      * 
74      * @param sql
75      * @return
76      */
77     public List findAllBySql(String sql);
78 
79 }

 

BaseDaoImpl

  1 package com.ssh.dao;
  2 
  3 import java.util.List;
  4 
  5 import org.hibernate.Query;
  6 import org.hibernate.SessionFactory;
  7 import org.springframework.transaction.annotation.Transactional;
  8 
  9 @Transactional
 10 public class BaseDaoImpl implements BaseDao{
 11     // @Autowired
 12         public SessionFactory sessionFactory;
 13 
 14         public SessionFactory getSessionFactory() {
 15             return sessionFactory;
 16         }
 17 
 18         public void setSessionFactory(SessionFactory sessionFactory) {
 19             this.sessionFactory = sessionFactory;
 20         }
 21 
 22 
 23         public void addObject(Object object) {
 24             sessionFactory.getCurrentSession().save(object);
 25         }
 26 
 27         public List findAllByHQL(String hql) {
 28             Query query = sessionFactory.getCurrentSession().createQuery(hql);
 29             return query.list();
 30         }
 31 
 32         public List findAllByHQL(String hql, Object[] args) {
 33             Query query = sessionFactory.getCurrentSession().createQuery(hql);
 34             for (int i = 0; i < args.length; i++) {
 35                 System.out.println(args[i]);
 36                 query.setParameter(i, args[i]);
 37             }
 38             return query.list();
 39         }
 40 
 41 
 42         public Object findObjectByHQL(String hql) {
 43             Query query = sessionFactory.getCurrentSession().createQuery(hql);
 44             List list = query.list();
 45             if (list.size() > 0) {
 46                 return list.get(0);
 47             }
 48             return null;
 49         }
 50 
 51         public Object findObjectByHQL(String hql, Object[] args) {
 52             Query query = sessionFactory.getCurrentSession().createQuery(hql);
 53             System.out.println(args[0]);
 54             for (int i = 0; i < args.length; i++) {
 55                 System.out.println(args[i]);
 56                 query.setParameter(i, args[i]);
 57             }
 58             List list = query.list();
 59             if (list.size() > 0) {
 60                 return list.get(0);
 61             }
 62             return null;
 63         }
 64 
 65         public List findPage(final String hql,final int page,final int size,final Object[] args) {
 66             Query query = sessionFactory.getCurrentSession().createQuery(hql);
 67             for (int i = 0; i < args.length; i++) {
 68                 query.setParameter(i, args[i]);
 69             }
 70             query.setMaxResults(size);
 71             query.setFirstResult(page);
 72             List<Object> list = query.list();
 73             return list;
 74         }
 75 
 76         public List findPage(final String hql, final int page, final int size) {
 77             Query query = sessionFactory.getCurrentSession().createQuery(hql);
 78             query.setMaxResults(size);
 79             query.setFirstResult(page);
 80             List<Object> list = query.list();
 81             return list;
 82         }
 83 
 84         public void delObject(Object object) {
 85             sessionFactory.getCurrentSession().delete(object);
 86         }
 87 
 88 
 89         public void updateObject(Object object) {
 90             sessionFactory.getCurrentSession().update(object);
 91         }
 92 
 93 
 94         public void updateObjectByHQL(String hql) {
 95             sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
 96         }
 97 
 98 
 99         public Object findObjectBySQL(String sql) {
100             Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
101 
102             List list = query.list();
103             if (list.size() > 0) {
104                 return list.get(0);
105             }
106             return null;
107         }
108 
109         public List findAllBySql(String sql) {
110             Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
111             return query.list();
112         }
113 
114         public void updateObjectByHQL(String hql, Object[] params) {
115             Query query = sessionFactory.getCurrentSession().createQuery(hql);
116             for (int i = 0; i < params.length; i++) {
117                 query.setParameter(i, params[i]);
118             }
119             query.executeUpdate();
120         }
121 
122 }

 

4、編寫shiro組件自定義Realm:

 1 package com.ssh.shiro;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.axis.handlers.SimpleAuthorizationHandler;
 6 import org.apache.shiro.authc.AuthenticationException;
 7 import org.apache.shiro.authc.AuthenticationInfo;
 8 import org.apache.shiro.authc.AuthenticationToken;
 9 import org.apache.shiro.authc.SimpleAuthenticationInfo;
10 import org.apache.shiro.authc.UsernamePasswordToken;
11 import org.apache.shiro.authz.AuthorizationInfo;
12 import org.apache.shiro.authz.SimpleAuthorizationInfo;
13 import org.apache.shiro.realm.AuthorizingRealm;
14 import org.apache.shiro.subject.PrincipalCollection;
15 
16 import com.ssh.entity.User;
17 import com.ssh.service.AccountService;
18 
19 /**
20  * 編寫自定義Realm
21  * @author dxyd
22  *
23  */
24 public class MyShiroRealm extends AuthorizingRealm{
25     
26      /**用戶的業務類**/  
27     private AccountService accountService;  
28       
29     public AccountService getAccountService() {  
30         return accountService;  
31     }  
32   
33     public void setAccountService(AccountService accountService) {  
34         this.accountService = accountService;  
35     }  
36      /*** 
37      * 獲取授權信息 
38      */  
39      //根據自己系統規則的需要編寫獲取授權信息,這里為了快速入門只獲取了用戶對應角色的資源url信息 
40     @Override
41     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
42         String username = (String)pc.fromRealm(getName()).iterator().next();
43         if(username!=null){
44             List<String> pers = accountService.getPermissionsByUserName(username); 
45             if(pers!=null && !pers.isEmpty()){
46                 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
47                 for(String each:pers){
48                     //將權限資源添加到用戶信息中  
49                     info.addStringPermission(each);
50                 }
51             }
52         }
53         return null;
54     }
55       /*** 
56      * 獲取認證信息 
57      */  
58     @Override
59     protected AuthenticationInfo doGetAuthenticationInfo(
60             AuthenticationToken at) throws AuthenticationException {
61     
62          
63         UsernamePasswordToken token = (UsernamePasswordToken) at;
64         // 通過表單接收的用戶名 
65         String username  = token.getUsername();
66         if(username!=null && !"".equals(username)){
67             User user = accountService.getUserByUserName(username);  
68              if (user != null) {  
69                     return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());  
70               }  
71         }
72         return null;
73     }
74 
75 }

 

 

上述類繼承了Shiro的AuthorizingRealm類 實現了AuthorizationInfo和AuthenticationInfo兩個方法,用於獲取用戶權限和認證用戶登錄信息

5、編寫LoginController:

 1 package com.ssh.controller;
 2 
 3 import org.apache.shiro.SecurityUtils;
 4 import org.apache.shiro.authc.UsernamePasswordToken;
 5 import org.apache.shiro.subject.Subject;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Controller;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RequestMethod;
10 import org.springframework.web.portlet.ModelAndView;
11 
12 import com.ssh.entity.User;
13 import com.ssh.service.AccountService;
14 
15 /****
16  * 用戶登錄Controller
17  * 
18  * @author Swinglife
19  * 
20  */
21 @Controller
22 public class LoginController {
23     // 處理用戶業務類
24     @Autowired
25     private AccountService accountService;
26 
27     /***
28      * 跳轉到登錄頁面
29      * 
30      * @return
31      */
32     @RequestMapping(value = "/toLogin")
33     public String toLogin() {
34         // 跳轉到/page/login.jsp頁面
35         return "login";
36     }
37 
38     /***
39      * 實現用戶登錄
40      * 
41      * @param username
42      * @param password
43      * @return
44      */
45     @RequestMapping(value = "/login",method = RequestMethod.POST)
46     public ModelAndView Login(String username, String password) {
47         ModelAndView mav = new ModelAndView();
48         User user = accountService.getUserByUserName(username);
49         if (user == null) {
50             mav.setView("toLogin");
51             mav.addObject("msg", "用戶不存在");
52             return mav;
53         }
54         if (!user.getPassword().equals(password)) {
55             mav.setView("toLogin");
56             mav.addObject("msg", "帳號密碼錯誤");
57             return mav;
58         }
59         SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());
60         // 登錄后存放進shiro token
61         UsernamePasswordToken token = new UsernamePasswordToken(
62                 user.getUsername(), user.getPassword());
63         Subject subject = SecurityUtils.getSubject();
64         subject.login(token);
65         // 登錄成功后會跳轉到successUrl配置的鏈接,不用管下面返回的鏈接。  
66         mav.setView("redirect:/home");
67         return mav;
68     }
69 
70 }

 

6、編寫信息認證成功后的跳轉頁面:

 1 package com.ssh.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 
 6 @Controller
 7 public class IndexController {
 8     @RequestMapping("home")
 9     public String index() {
10         System.out.println("登錄成功");
11         return "home";
12     }
13 }

 

7、Shiro的配置文件.xml

spring-shiro.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6                 http://www.springframework.org/schema/context
 7                  http://www.springframework.org/schema/context/spring-context-3.2.xsd
 8                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
 9                  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
10                  
11     <!-- shiro-all.jar 
12     filterChainDefinitions:apache 
13     shiro通過filterChainDefinitions參數來分配鏈接的過濾,
14     資源過濾有常用的以下幾個參數:
15     authc 表示需要認證的鏈接
16     perms[/url] 表示該鏈接需要擁有對應的資源/權限才能訪問
17     roles[admin] 表示需要對應的角色才能訪問
18     perms[admin:url] 表示需要對應角色的資源才能訪問
19     
20     -->             
21     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
22         <property name="securityManager" ref="securityManager" />
23         <property name="loginUrl" value="/toLogin" />
24         <property name="successUrl" value="/home" />
25         <property name="unauthorizedUrl" value="/403.do" />
26          
27         <property name="filterChainDefinitions">
28             <value>
29                 /toLogin = authc <!-- authc 表示需要認證才能訪問的頁面 -->
30                 /home = authc, perms[/home]  <!-- perms 表示需要該權限才能訪問的頁面 -->
31             </value>
32         </property>
33     </bean>
34     
35     <bean id="myShiroRealm" class="com.ssh.shiro.MyShiroRealm">
36         <!-- businessManager 用來實現用戶名密碼的查詢 -->
37         <property name="accountService" ref="accountService" />
38     </bean>     
39     <!-- shiro-all.jar -->
40     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
41         <property name="realm" ref="myShiroRealm"></property>
42     </bean>
43     
44     <bean id="accountService" class="com.ssh.service.AccountService"></bean>
45 
46     <!-- <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> 
47         <property name="cacheManager" ref="cacheManager" /> </bean> -->
48 </beans>

loginUrl 用於配置登陸頁

successUrl 用於配置登錄成功后返回的頁面,不過該參數只會在當登錄頁面中並沒有任何返回頁面時才會生效,否則會跳轉到登錄Controller中的指定頁面。

unauthorizedUrl 用於配置沒有權限訪問頁面時跳轉的頁面


filterChainDefinitions:apache shiro通過filterChainDefinitions參數來分配鏈接的過濾,資源過濾有常用的以下幾個參數:

1、authc 表示需要認證的鏈接

2、perms[/url] 表示該鏈接需要擁有對應的資源/權限才能訪問

3、roles[admin] 表示需要對應的角色才能訪問

4、perms[admin:url] 表示需要對應角色的資源才能訪問

 

 

spring-common.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" 
 3   xmlns:aop="http://www.springframework.org/schema/aop" 
 4   xmlns:cache="http://www.springframework.org/schema/cache" 
 5   xmlns:context="http://www.springframework.org/schema/context" 
 6   xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
 7   xmlns:jee="http://www.springframework.org/schema/jee" 
 8   xmlns:jms="http://www.springframework.org/schema/jms" 
 9   xmlns:lang="http://www.springframework.org/schema/lang" 
10   xmlns:mvc="http://www.springframework.org/schema/mvc" 
11   xmlns:oxm="http://www.springframework.org/schema/oxm" 
12   xmlns:task="http://www.springframework.org/schema/task" 
13   xmlns:tx="http://www.springframework.org/schema/tx" 
14   xmlns:util="http://www.springframework.org/schema/util" 
15   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
16   xsi:schemaLocation="http://www.springframework.org/schema/beans
17       http://www.springframework.org/schema/beans/spring-beans.xsd
18     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
19     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
20     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
21     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
22     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
23     http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.2.xsd
24     http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
25     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
26     http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd
27     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
28     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
29     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
30     
31     <!--掃描映射  -->
32     <context:component-scan base-package="com.ssh"></context:component-scan>
33     
34     <!-- 引入property配置文件 -->
35     <context:property-placeholder location="classpath:prop/jdbc.properties"></context:property-placeholder>
36     <!-- 配置數據源 -->
37     <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
38         <property name="driverClassName" value="${jdbc.mysql.driverClassName}"></property>
39         <property name="url" value="${jdbc.mysql.url}"></property>
40         <property name="username" value="${jdbc.mysql.username}"></property>
41         <property name="password" value="${jdbc.mysql.password}"></property>
42         <!-- 初始化連接大小
43         <property name="initialSize" value="${jdbc.initialSize}"></property> -->
44         <!-- 連接池最大數量 
45         <property name="maxActive" value="${jdbc.maxActive}"></property>-->
46         <!-- 連接池最大空閑 -->
47         <!-- <property name="maxIdle" value="${maxIdle}"></property> -->
48         <!-- 連接池最小空閑 
49         <property name="minIdle" value="${jdbc.minIdle}"></property>-->
50         <!-- 獲取連接最大等待時間 
51         <property name="maxWait" value="${jdbc.maxWait}"></property>-->
52     </bean>
53     
54     <!-- 配置SessionFactory -->
55     <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
56         <property name="dataSource" ref="dataSource"></property>
57         <property name="hibernateProperties">
58             <props>
59                 <prop key="hibernate.dialect">${jdbc.mysql.dialect}</prop>
60                 <prop key="hibernate.hbm2ddl.auto">update</prop>
61                 <!--是否顯示sql語句 我在這里是顯示的  -->
62                 <prop key="hibernate.show_sql">true</prop>
63                 <!--格式化顯示sql語句  -->
64                 <prop key="hibernate.format_sql">true</prop>
65             </props>
66         </property>
67         <!-- 自動掃描制定位置下的實體進行映射  --> 
68         <property name="packagesToScan" value="com.ssh.entity"></property>
69     </bean>
70     
71     <!-- 配置一個事務管理器 -->
72     <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager">
73         <property name="sessionFactory" ref="sessionFactory">
74     </property></bean>
75     
76     <!-- 應該是開啟事物 -->
77     <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
78     
79     <!-- baseDao -->
80     <bean id="dao" class="com.ssh.dao.BaseDaoImpl">
81         <property name="sessionFactory" ref="sessionFactory"></property>
82     </bean>
83 </beans>

 

spring-mvc.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans 
 3     http://www.springframework.org/schema/beans/spring-beans.xsd
 4     http://www.springframework.org/schema/context
 5     http://www.springframework.org/schema/context/spring-context-3.2.xsd
 6     http://www.springframework.org/schema/mvc
 7     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 8     
 9     <!-- 注解掃描包 -->
10     <context:component-scan base-package="com.ssh"></context:component-scan>
11 
12     <!-- 開啟注解 -->
13     <mvc:annotation-driven></mvc:annotation-driven>    
14 
15     <!-- 定義視圖解析器 -->    
16     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
17         <property name="prefix" value="/WEB-INF/page/"></property>
18         <property name="suffix" value=".jsp"></property>
19     </bean>
20     <import resource="spring-common.xml"/>
21     <import resource="spring-shiro.xml"/>
22 </beans>

 

 

 

 

8、登陸頁login.jsp

 1     <body>  
 2       
 3     <h1>user login</h1>  
 4     <form action="login" method="post">  
 5     username:<input type="text" name="username"><p>  
 6     password:<input type="password" name="password">  
 7     <p>  
 8     ${msg }  
 9     <input type="submit" value="submit">  
10     </form>  
11     </body>  



9、運行程序

在數據庫中添加一條用戶、角色、以及權限數據,並且在關聯表中添加一條關聯數據:





 


 

在瀏覽器中訪問: home頁面 就會跳轉到登錄頁面:  




最后輸入 賬號密碼 就會跳轉到登錄成功頁面。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM