springmvc,shiro整合

继之前搭好的框架基础上整合shiro配置。

地址:http://www.cnblogs.com/mangyang/p/5168291.html

一、pom.xml

maven添加shiro的包支持

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring_v1</groupId>
  <artifactId>spring_v1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <springmvc.version>4.0.2.RELEASE</springmvc.version>
    <log4j.version>1.6.6</log4j.version>
    <mysql-connector-java.version>5.1.34</mysql-connector-java.version>
    <shiro.version>1.2.3</shiro.version>
  </properties>

  <dependencies>
      <!-- spring-mvc -->
     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${springmvc.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.webflow</groupId>
        <artifactId>spring-webflow</artifactId>
        <version>2.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${springmvc.version}</version>
    </dependency>
    <!-- freemarker -->
    <dependency>
          <groupId>org.freemarker</groupId>
          <artifactId>freemarker</artifactId>
          <version>2.3.20</version>
    </dependency>
    <!-- 阿里jdbc -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>0.2.21</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.1.24</version>
    </dependency>
    <!-- mybatis -->
    <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.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.0.2</version>
    </dependency>
    <!-- mysql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>
    <!-- 解决@ResponseBody返回JSON数据,页面抛出406错误的解决方案。 -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <!--ehcache 相关包 -->
       <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.6.9</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-web</artifactId>
        <version>2.0.4</version>
    </dependency>
    <!-- shiro -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>${shiro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-ehcache</artifactId>
        <version>${shiro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>${shiro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>${shiro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-quartz</artifactId>
        <version>${shiro.version}</version>
    </dependency>
   <!-- commons -->
   <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-lang3</artifactId>
       <version>3.1</version>
   </dependency>
   <!-- servlet -->
   <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>servlet-api</artifactId>
       <version>2.5</version>
   <scope>provided</scope>
    </dependency>
    <!-- json -->
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>
  </dependencies>
</project>

二、web.xml

添加shiro拦截配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>spring_v1</display-name>

    <!-- 集成Web环境的通用配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:/spring-application.xml,
            classpath*:/spring-shiro.xml
        </param-value>
    </context-param>

    <!-- spring上下文 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- springMVC 配置 -->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Shiro配置 -->
    <filter>
      <filter-name>shiroFilter</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>shiroFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 编码格式UTF-8 -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

三、spring-shiro.xml

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置权限管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!-- ref对应我们写的realm  Shiro -->
        <property name="realm" ref="myRealm"/>
    </bean>  

    <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
         <!-- 调用我们配置的权限管理器 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 配置我们的登录请求地址 -->
        <property name="loginUrl" value="/login"/>
        <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
        <property name="successUrl" value="/show"/>
        <!-- 权限配置 -->
        <property name="filterChainDefinitions">
            <value>
                /**= authc
            </value>
        </property>
    </bean>

    <bean id="myRealm" class="com.shiro.MyRealm">
        <property name="authorizationCacheName" value="authorization" />
        <property name="authenticationTokenClass" value="com.shiro.AdminToken" />
    </bean>
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> 

</beans>

 AdminToken.java

package com.shiro;

import org.apache.shiro.authc.UsernamePasswordToken;

public class AdminToken extends UsernamePasswordToken {
	public AdminToken(String username, final String password,
			final boolean rememberMe, final String host) {
		super(username, password, rememberMe, host);
	}
}

MyRealm.java

package com.shiro;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.entity.UserRoleAuth;
import com.service.UserRoleAuthService;

public class MyRealm extends AuthorizingRealm{

	@Autowired
	private UserRoleAuthService userRoleAuthService;

	/*
	 * 获取授权信息
	 * 2016.03.11
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName=(String)principals.iterator().next();

		List<UserRoleAuth> list = userRoleAuthService.findByName(userName);

		//赋予角色
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		for (UserRoleAuth sra : list) {
			//保存不重复角色
			if(info.getRoles()==null ||(!info.getRoles().contains(sra.getRoleName())))
			{
				info.addRole(sra.getRoleName());
			}
			//保存不重复权限
			Collection<String> auths = new HashSet<String>();

			if(!auths.contains(sra.getAuthCode()))
			{
				auths.add(sra.getAuthCode());
			}
			info.addStringPermissions(auths);
		}

		return info;
	}

	/*
	 * 获取认证信息
	 * 2016.03.11
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		//获取用户登陆令牌
		AdminToken myToken = (AdminToken) token;
		//获取登陆账号
		String username = myToken.getUsername();
		//获取登陆密码
		String password = new String(myToken.getPassword());

		return new SimpleAuthenticationInfo(username, password, getName());
	}
	@Override
	public boolean supports(AuthenticationToken token) {
		return super.supports(token);
	}

}

sql地址:http://pan.baidu.com/s/1dEZMvYh  配合sql生成工具 实体类等。

LoginAction.java 的方法(传入账号密码)

@RequestMapping(value = "", method = RequestMethod.POST)
	public String login(HttpServletRequest request, HttpServletResponse response,
			String userName, String userPsw) throws Exception {

		Subject user = SecurityUtils.getSubject();

		AdminToken token = new AdminToken(userName, userPsw, true, request.getRemoteAddr());
		token.setRememberMe(true);
		user.login(token);

		return "show";
	}

show.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <shiro:hasPermission name="code01">code01权限用户显示此内容</shiro:hasPermission>
  <shiro:hasPermission name="code02">code02权限用户显示此内容</shiro:hasPermission>
    <shiro:hasPermission name="code03">code03权限用户显示此内容</shiro:hasPermission>
 <shiro:hasRole name="superAdmin">superAdmin角色登录显示此内容</shiro:hasRole>
  <shiro:hasRole name="admin">admin角色登录显示此内容</shiro:hasRole>
  this is show
</body>
</html>

完成!

时间: 2024-11-04 18:32:11

springmvc,shiro整合的相关文章

SpringMVC+Shiro整合配置文件详解

在项目中xml文件的配置是必不可少的,特别是SpringMVC框架.但是几乎所有项目的配置都是大同小异,很多人都是直接复制黏贴了事,不少人对其具体含义及用途都不甚全知.本片文章将正对项目中常用的框架SpringMVC+Shiro进行整合,并对其中关键和部分常识性问题进行注释讲解,方便在以后的项目编写中查阅和熟悉. 1.web.xml文件的配置 所有javaweb项目第一步要做的就是对web.xml文件进行配置. 1 <?xml version="1.0" encoding=&qu

springmvc shiro整合cas单点登入

shiro cas分为登入跟登出 maven依赖: <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.apache.shiro</gr

Spring+SpringMVC+Hibernate 与 shiro 整合步骤

通过这篇文章你可以了解到: SSH 三大框架(spring + springMVC + Hiberante) 与 shiro 安全验证框架如何整合: 通过一个示例,快速理解 shiro 框架. [TOC] 1. 业务需求分析 用户 N - 角色 N - 权限 N 我们可以想象一下,在平时工作中的职务,比如:业务经理,部门主管等,他们拥有很多的权力,而一个公司中不会只有一个业务经理,也不会只有一个部门主管,如果我们要给不同的人分配职务权力时,每次都是具体的条条框框去分配,人累心也累.而如果我们事先

SpringMVC + MyBatis整合 【转】

环境:spring3.1.1+mybatis3.2.8+mybatis-spring1.2.3 网络上关于这个架构的搭建文章,实在是太多了,本文是对于本人初次搭建时的一些注意点的整理. 主要是一些配置文件的内容和架构的目录. 0. project 目录 1. spring-resources.xml 这个文件是用来完成spring和mybatis的整合的xml.注意properties文件的读入方式. <?xml version="1.0" encoding="UTF-

shiro整合spring配置

shiro应用到项目中,一般都是通过spring来管理.下面就如何把shiro整理到spring中进行了讲解,及给出了配置的步骤: 一.pom.xml文件配置 本例子主要是介绍maven管理的web项目进行配置介绍,因此,首先需建立好一个maven管理的web项目(可参考本博客创建maven管理的web项目). pom.xml文件配置,主要是添加相关依赖的jar支持.因为整合到spring中需添加spring支持.具体配置参考配置代码: 1 <project xmlns="http://m

SpringBoot与Shiro整合

修改pom.xml: <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/xsd/maven-4.0.0.xsd"> <

【SpringMVC学习04】Spring、MyBatis和SpringMVC的整合

前两篇springmvc的文章中都没有和mybatis整合,都是使用静态数据来模拟的,但是springmvc开发不可能不整合mybatis,另外mybatis和spring的整合我之前学习mybatis的时候有写过一篇,但是仅仅是整合mybatis和spring,所以这篇文章我系统的总结一下spring.mybatis和springmvc三个框架的整合(后面学习到maven时,我会再写一篇使用maven整合的文章,这篇没有用到maven). 1. jar包管理 我之前有写过一篇spring.hi

SpringMVC + MyBatis整合

环境:spring3.1.1+mybatis3.2.8+mybatis-spring1.2.3 网络上关于这个架构的搭建文章,实在是太多了,本文是对于本人初次搭建时的一些注意点的整理. 主要是一些配置文件的内容和架构的目录. 0. project 目录 1. spring-resources.xml 这个文件是用来完成spring和mybatis的整合的xml.注意properties文件的读入方式. <?xml version="1.0" encoding="UTF-

之前SpringMVC+Mybatis整合,现在加上AOP

之前SpringMvc和mybatis整合的例子:http://www.cnblogs.com/acehalo/p/3901809.html Controller类增加方法,以便测试: @RequestMapping(value = "/aopTest") @ResponseBody public String aopTest(HttpServletRequest request) { for (int i = 0; i < 3; i++) { aopServiceTest.do