日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringMvc 集成 shiro 实现权限角色管理-maven

發布時間:2025/3/18 javascript 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringMvc 集成 shiro 实现权限角色管理-maven 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

SpringMvc 集成 shiro 實現權限角色管理

1、項目清單展示


2、項目源碼解析

?1)spring-context.xml ------spring 父上下文 <?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:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.1.xsd"><context:annotation-config /><!-- 默認掃描的包路徑 --><context:component-scan base-package="com" /><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager" /><property name="successUrl" value="/member/loginsuccess.jsp" /><property name="loginUrl" value="/login.jsp" /><property name="unauthorizedUrl" value="/error.html" /><property name="filters"><map><entry key="authc" value-ref="shiro"></entry></map></property><!-- 下面value值的第一個'/'代表的路徑是相對于HttpServletRequest.getContextPath()的值來的 --><!-- anon:它對應的過濾器里面是空的,什么都沒做,這里.do和.jsp后面的*表示參數,比方說login.jsp?main這種 --><!-- authc:該過濾器下的頁面必須驗證后才能訪問,它是Shiro內置的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter --><property name="filterChainDefinitions"><value>/login.jsp=anon/member/loginsuccess.jsp=anon/error.html=authc/member/**=authc,roles["edit"]/edit=authc,roles["edit"],perms["delete1"]/getJson/**=anon</value></property></bean><bean id="shiro" class="com.cat.shiro.ShiroFilter"></bean><bean id="shiroRealm" class="com.cat.shiro.ShiroRealm" /><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="shiroRealm" /><!-- 需要使用cache的話加上這句 <property name="cacheManager" ref="shiroEhcacheManager" /> --></bean><!-- 用戶授權信息Cache, 采用EhCache,需要的話就配置上此信息 <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" /> </bean> --><!-- 保證實現了Shiro內部lifecycle函數的bean執行 --><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /><!-- 開啟Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP掃描使用Shiro注解的類,并在必要時進行安全邏輯驗證 --><!-- 配置以下兩個bean即可實現此功能 --><!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run --><!-- 由于本例中并未使用Shiro注解,故注釋掉這兩個bean(個人覺得將權限通過注解的方式硬編碼在程序中,查看起來不是很方便,沒必要使用) --><beanclass="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"depends-on="lifecycleBeanPostProcessor"><property name="proxyTargetClass" value="true" /></bean><beanclass="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"><property name="securityManager" ref="securityManager" /></bean> </beans>
?2)dispatcher-servlet.xml---------springMvc 配置文件 <?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:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"default-lazy-init="true"><!-- 添加注解驅動 --><context:annotation-config /><mvc:annotation-driven /><!-- 默認掃描的包路徑 --><context:component-scan base-package="com" /><mvc:default-servlet-handler/><!-- mvc返回頁面的配置 --><bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 模板路徑為WEB-INF/pages/ --><property name="prefix"><value>/WEB-INF/</value></property><!-- 視圖模板后綴為.JSP --><property name="suffix"><value>.jsp</value></property></bean> </beans>
?3)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context.xml</param-value></context-param> <!-- shiro filter 的配置要在別的配置之前,保證能夠攔截到所有的請求 --><filter><filter-name>shiroFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><init-param><param-name>targetFilterLifecycle</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>shiroFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/dispatcher-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list> </web-app>

? 4)順序源碼

package com.cat.shiro;import java.io.IOException; import java.security.Principal;import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject;import com.cat.spring.entity.Role; import com.cat.spring.entity.User;/*** @author chenlf* * 2014-3-24*/ public class ShiroFilter implements Filter {@Overridepublic void destroy() {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {System.out.println("啟用filter........");HttpServletRequest httpRequest = (HttpServletRequest) request;HttpServletResponse httpResponse = (HttpServletResponse) response;Principal principal = httpRequest.getUserPrincipal();System.out.println(principal);System.out.println("getUserPrincipal is :" + principal);if (principal != null) {Subject subjects = SecurityUtils.getSubject();// 為了簡單,這里初始化一個用戶。實際項目項目中應該去數據庫里通過名字取用戶:// 例如:User user = userService.getByAccount(principal.getName());User user = new User();user.setName("shiro");user.setPassword("123456");user.setRole(new Role("edit"));if (user.getName().equals(principal.getName())) {UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());subjects = SecurityUtils.getSubject();subjects.login(token);subjects.getSession();} else {// 如果用戶為空,則subjects信息登出if (subjects != null) {subjects.logout();}}}chain.doFilter(httpRequest, httpResponse);}@Overridepublic void init(FilterConfig arg0) throws ServletException {} }
package com.cat.shiro;import java.util.ArrayList; import java.util.List;import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject;import com.cat.spring.entity.Role; import com.cat.spring.entity.User; import com.cat.spring.service.UserService;/*** 該類從principals中取得用戶名稱進行匹配,在principals中默認保存了當前登陸人的用戶名稱,從而將該用戶的角色加入到作用域中;*/ public class ShiroRealm extends AuthorizingRealm {//登陸第二步,通過用戶信息將其權限和角色加入作用域中,達到驗證的功能@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {// 根據用戶配置用戶與權限if (principals == null) {throw new AuthorizationException("PrincipalCollection method argument cannot be null.");}String name = (String) getAvailablePrincipal(principals);List<String> roles = new ArrayList<String>();List<String> permissions = new ArrayList<String>();// 通過當前登陸用戶的姓名查找到相應的用戶的所有信息User user = UserService.getUserByName(name);Role role = user.getRole();if (user.getName().equals(name)) {if (user.getRole() != null) {// 裝配用戶的角色和權限 deleteroles.add(user.getRole().getName());permissions.add("delete");}} else {throw new AuthorizationException();}SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();// 為用戶設置角色和權限info.addRoles(roles);info.addStringPermissions(permissions);return info;}/*** 驗證當前登錄的Subject* @see 經測試:本例中該方法的調用時機為LoginController.login()方法中執行Subject.login()時*/@SuppressWarnings("unused")@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {// 登陸后的操作,此處為登陸有的第一步操作,從LoginController.login中調用了此處的tokenUsernamePasswordToken token = (UsernamePasswordToken) authcToken;System.out.println("token is :" + token);// 簡單默認一個用戶,實際項目應User user = userService.getByAccount(token.getUsername());// 下面通過讀取token中的數據重新封裝了一個userString pwd = new String(token.getPassword());User user = new User(token.getUsername(), pwd);if (user == null) {throw new AuthorizationException();}SimpleAuthenticationInfo info = null;if (user.getName().equals(token.getUsername())) {info = new SimpleAuthenticationInfo(user.getName(),user.getPassword(), getName());}//將該User村放入session作用域中//this.setSession("user", user);return info;}/*** 將一些數據放到ShiroSession中,以便于其它地方使用* 比如Controller,使用時直接用HttpSession.getAttribute(key)就可以取到*/@SuppressWarnings("unused")private void setSession(Object key, Object value) {Subject currentUser = SecurityUtils.getSubject();if (null != currentUser) {Session session = currentUser.getSession();System.out.println("Session默認超時時間為[" + session.getTimeout() + "]毫秒");if (null != session) {session.setAttribute(key, value);}}}}
/*** */ package com.cat.spring.controller;import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;import com.cat.spring.entity.Role; import com.cat.spring.entity.User;@Controller public class LoginController {@RequestMapping(value = "/login", method = RequestMethod.GET)public ModelAndView login() {return new ModelAndView("/login");}/*** 處理登陸配置*/@RequestMapping(value = "/submit", method = RequestMethod.POST)public ModelAndView submit(String username, String password) {User user = new User("shiro", "123456");user.setRole(new Role("edit"));try {// 如果登陸成功if (user.getName().equals(username) && user.getPassword().equals(password)) {UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword().toString());Subject subject = SecurityUtils.getSubject();subject.login(token);}} catch (Exception e) {e.printStackTrace();}return new ModelAndView("redirect:/member/index.jsp");} }
/*** 該類沒什么用處,還要研究*/ package com.cat.spring.controller.member;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;/*** @author chenlf* * 2014-3-24*/ @Controller @RequestMapping(value = "/member") //會員中心要被攔截 public class IndexController {// 攔截/index.htm 方法為GET的請求@RequestMapping(value = "/index", method = RequestMethod.GET)public ModelAndView index() {ModelAndView view = new ModelAndView();view.setViewName("/member/index");return view;}}
package com.cat.spring.entity;public class Role { private String name;public String getName() {return name; }public void setName(String name) {this.name = name; } public Role() {// TODO Auto-generated constructor stub }public Role(String name) {this.name = name; } }
package com.cat.spring.entity;public class User { private String name; private String password; private Role role;public Role getRole() {return role; }public void setRole(Role role) {this.role = role; }public String getName() {return name; }public void setName(String name) {this.name = name; }public String getPassword() {return password; }public void setPassword(String password) {this.password = password; }public User() {// TODO Auto-generated constructor stub }public User(String name, String password) {this.name = name;this.password = password; }}
package com.cat.spring.service;import org.springframework.stereotype.Repository;import com.cat.spring.entity.Role; import com.cat.spring.entity.User; @Repository public class UserService { public static User getUserByName(String name){//通過姓名從數據庫中讀取到相應的用戶User user = new User(name, "123456");user.setRole(new Role("edit"));return user; } }
package com.lives.shiro.controller;import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;@Controller public class HelloController {@RequestMapping("/getJson")public String getJson() {System.out.println("進入colloer");return "success";}@RequestMapping("/edit")public String hello2() {return "redirect:/member/index.jsp";} }

3、pox.xml-maven管理

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.lives</groupId><artifactId>lives_shiro</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>lives_shiro Maven Webapp</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring.version>3.1.1.RELEASE</spring.version></properties><dependencies><!-- spring begin --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.4.1</version></dependency><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-core-asl</artifactId><version>1.9.13</version></dependency><dependency><groupId>javax.ws.rs</groupId><artifactId>javax.ws.rs-api</artifactId><version>2.0</version></dependency><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.7.3</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><!-- spring end --><!-- servlet --><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>3.0-alpha-1</version></dependency><!-- mybatis begin --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.2</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.0</version></dependency><!-- mybatis end --><!-- log4j --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.5</version></dependency><!-- httpclient begin --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.3.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpasyncclient</artifactId><version>4.0.2</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency><!-- httpclient end --><!-- springmvc rabbitmq --><dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><version>3.3.0</version></dependency><dependency><groupId>org.springframework.amqp</groupId><artifactId>spring-amqp</artifactId><version>1.3.0.RELEASE</version></dependency><dependency><groupId>org.springframework.amqp</groupId><artifactId>spring-rabbit</artifactId><version>1.3.0.RELEASE</version></dependency><dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId><version>1.0.3.RELEASE</version></dependency><!--json-lib --><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><!-- springmvc redis --><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>1.3.2.RELEASE</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.4.2</version></dependency><!-- 漢語拼音包 --><dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>2.5.0</version></dependency><!-- 阿里 德魯伊連接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.5</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.30</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><!-- shiro 使用maven --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.2</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>1.2.2</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.2.2</version></dependency><dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>2.2.2</version></dependency></dependencies><profiles><profile><id>dev</id><properties><package.environment>dev</package.environment></properties><activation><activeByDefault>true</activeByDefault></activation></profile><profile><id>test</id><properties><package.environment>test</package.environment></properties></profile><profile><id>prod</id><properties><package.environment>prod</package.environment></properties></profile></profiles><build><finalName>lives_shiro</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.8</source><target>1.8</target><archive><addMavenDescriptor>false</addMavenDescriptor></archive><webResources><resource><directory>src/main/resources/properties/${package.environment}</directory><targetPath>WEB-INF/classes</targetPath><filtering>true</filtering></resource></webResources></configuration></plugin></plugins></build> </project>

4、filterChainDefinitions配置講解

http://www.cppblog.com/guojingjia2006/archive/2014/05/14/206956.html

5、項目中webapp目錄的下載

http://download.csdn.net/detail/u014201191/8767629


轉載于:https://my.oschina.net/gaoguofan/blog/753307

總結

以上是生活随笔為你收集整理的SpringMvc 集成 shiro 实现权限角色管理-maven的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。