由于shiro在web.xml中配置属于过滤器,其中在web.xml中的加载顺序为: <context-param>(上下文) > listener > filter > servlet>interceptor,

可见shiroFilter是早于SpringMVC的,所以Controller无法注册service,同时Realm中注册的service为空,我百度的各种方法都试过了仍然不好用。

最终我把spring整合shiro的配置直接全部拉到了spring.xml(整合mabatis,redis)配置文件的最下面。

如果大家想看可以参考下面

spring.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"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
default-autowire="byName" default-lazy-init="false"> <!-- 配置注解处理器 -->
<context:annotation-config/> <!-- 自动注册service -->
<context:component-scan base-package="com.smart.service"/>
<!--扫描redis配置文件-->
<context:property-placeholder ignore-unresolvable="true" location="classpath:redis.properties"/> <!--Spring整合Redis-->
<!--设置连接池-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大空闲连接数 -->
<property name="maxIdle" value="${redis.maxIdle}"/>
<!-- 最大连接数 -->
<property name="maxTotal" value="${redis.maxTotal}" />
<!-- 每次释放连接的最大数目 -->
<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" />
<!-- 释放连接的扫描间隔(毫秒) -->
<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />
<!-- 连接最小空闲时间 -->
<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" />
<!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<!-- 在获取连接的时候检查有效性, 默认false -->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<property name="testOnReturn" value="${redis.testOnReturn}" />
<!-- 在空闲时检查有效性, 默认false -->
<property name="testWhileIdle" value="${redis.testWhileIdle}" />
<!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
<property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" />
</bean> <!-- jedis客户端单机版 -->
<bean id="redisClient" class="redis.clients.jedis.JedisPool">
<constructor-arg name="host" value="${redis.host}"></constructor-arg>
<constructor-arg name="port" value="${redis.port}"></constructor-arg>
<constructor-arg name="password" value="${redis.password}"></constructor-arg>
<constructor-arg name="poolConfig" ref="poolConfig"></constructor-arg>
<constructor-arg name="timeout" value="100000"></constructor-arg>
</bean>
<bean id="JedisClient" class="com.smart.redis.JedisClientSingle"/> <!--Spring整合Mabatis-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/bookmanager?characterEncoding=utf8"
p:username="root" p:password="960521" p:maxActive="10" p:maxIdle="10"
p:validationQuery="SELECT 1" p:testOnBorrow="true">
</bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池-->
<property name="dataSource" ref="dataSource" />
<!--configLocation属性指定mybatis的核心配置文件-->
<property name="configLocation" value="classpath:mybatis.xml" />
<!-- 所有配置的mapper文件 -->
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.smart.dao"/>
</bean> <!-- 开启注解方式声明事务 -->
<tx:annotation-driven transaction-manager="transactionManager" /> <!--这里开始整合redis-->
<!--Spring整合shiro-->
<!-- 配置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="/maSystem" />
<!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
<property name="unauthorizedUrl" value="/error" />
<property name="filters">
<util:map>
<entry key="logout" value-ref="logoutFilter" />
</util:map>
</property>
<!-- 权限配置 -->
<property name="filterChainDefinitions">
<value>
<!-- anon表示此地址不需要任何权限即可访问 -->
/error=anon
/meList=anon
/maSystem=anon
/login=anon
/listBook.do=anon
/UserType.do=anon
/style/**=anon
/logout=logout
<!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login -->
/** = authc
</value>
</property>
</bean>
<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/login" />
</bean> <!-- 凭证匹配器
<bean id="passwordMatcher" class="org.apache.shiro.authc.credential.PasswordMatcher">
<property name="passwordService" ref="passwordService" />
</bean>
<bean id="passwordService"
class="org.apache.shiro.authc.credential.DefaultPasswordService">
<property name="hashService" ref="hashService"></property>
<property name="hashFormat" ref="hashFormat"></property>
<property name="hashFormatFactory" ref="hashFormatFactory"></property>
</bean>
<bean id="hashService" class="org.apache.shiro.crypto.hash.DefaultHashService"></bean>
<bean id="hashFormat" class="org.apache.shiro.crypto.hash.format.Shiro1CryptFormat"></bean>
<bean id="hashFormatFactory"
class="org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory">
</bean>--> <!-- 缓存管理器 使用Ehcache实现
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean>--> <!-- 会话ID生成器-->
<bean id="sessionIdGenerator"
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
<!-- 会话Cookie模板 关闭浏览器立即失效-->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="sid" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="-1" />
</bean>
<!-- 会话DAO-->
<bean id="sessionDAO"
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="sessionIdGenerator" ref="sessionIdGenerator" />
</bean>
<!-- 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存-->
<bean name="sessionValidationScheduler"
class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
<property name="interval" value="1800000" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<!-- 会话管理器-->
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- 全局会话超时时间(单位毫秒),默认30分钟-->
<property name="globalSessionTimeout" value="1800000" />
<property name="deleteInvalidSessions" value="true" />
<property name="sessionValidationSchedulerEnabled" value="true" />
<property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
<property name="sessionDAO" ref="sessionDAO" />
<property name="sessionIdCookieEnabled" value="true" />
<property name="sessionIdCookie" ref="sessionIdCookie" />
</bean> <!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
<!-- 使用下面配置的缓存管理器 -->
<property name="cacheManager" ref="cacheManager" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean> <!-- 注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 -->
<bean id="userRealm" class="com.smart.shiro.UserRealm" lazy-init="false">
<!--
<property name="credentialsMatcher" ref="passwordMatcher"/>
<property name="cachingEnabled" value="false"/>-->
</bean> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
<!-- Shiro生命周期处理器 -->
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> </beans>

SpringMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!--自动扫描controller-->
<context:component-scan base-package="com.smart.controller" />
<!--开启注解-->
<mvc:annotation-driven /> <!--视图解析-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限,单位为字节(10MB) -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>

<!--Shiro配置-->
<!--
1.配置lifecycleBeanPostProcessor,可以在Spring IOC容器中调用shiro的生命周期方法.--> <bean class="org.apache.shiro.spring.LifecycleBeanPostProcessor" id="lifecycleBeanPostProcessor" /> <!--
2.启用Spring IOC容器Shiro注解,但必须配置了lifecycleBeanPostProcessor后才可以使用--> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" /> <!--
3.开启Spring AOC Shiro注解支持--> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean> </beans>

然后把这两个文件在web.xml中加载即可(同整合SSM时一样,无需改变),然后再添加shiro的过滤器即可

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd"
id="WebApp_ID" version="2.4"> <!--其中在web.xml中的加载顺序为: <context-param>(上下文) > listener > filter > servlet>interceptor-->
<display-name>SSM</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!--加载配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextCleanupListener</listener-class>
</listener> <!--字符过滤器-->
<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> <!-- shiro 安全过滤器
DelegatingFilterProxy作用是自动到spring容器查找名字为shiroFilter(filter-name)的bean并把所有Filter的操作委托给它-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
<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> <!--配置静态资源-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/style/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/public/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping> <!--Spring MVC 核心控制器DispatcherServlet-->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--如果springMVC配置文件名字为spring-mvc-servlet.xml,且和web.xml在同一级目录下无需配置下面内容,否则需要配置-->
<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> </web-app>

既然都写到这份上了,我就索性把所有代码都写一下

UserRealm

package com.smart.shiro;

import javax.annotation.Resource;

import com.smart.bean.User;
import com.smart.service.UserService;
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.UnknownAccountException;
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; public class UserRealm extends AuthorizingRealm { @Autowired
private UserService userService; @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String)principals.getPrimaryPrincipal();
System.out.println(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
if(userService==null){
userService = SpringBeanFactoryUtils.getBean("userService");
}else {
System.out.println("UserRealm is not NULL");
}
authorizationInfo.setRoles(userService.findRoles(username));
authorizationInfo.setStringPermissions(userService.findPermissions(username)); return authorizationInfo;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String)token.getPrincipal();
System.out.println(username);
if(userService==null){
userService = SpringBeanFactoryUtils.getBean("userService");
}else {
System.out.println("UserRealmsss is not NULL");
}
System.out.println(username);
User user = userService.findByGeNumber(username); if(user == null) {
throw new UnknownAccountException();//没找到帐号
} //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user.getGeNumber(),//用户名
user.getPassword(),
getName() //realm name
); return authenticationInfo;
} }

Controller

@RequestMapping(value = "/UserType.do")
@ResponseBody
public Map<String,Object> Login(String geNumber, String password){
System.out.println(geNumber+","+password);
Map<String,Object> map = new HashMap<String,Object>();
//主体,当前状态为没有认证的状态“未认证”
Subject subject = SecurityUtils.getSubject();
// 登录后存放进shiro token
UsernamePasswordToken token=new UsernamePasswordToken(geNumber,password);
//登录方法(认证是否通过)
//使用subject调用securityManager,安全管理器调用Realm
try {
//利用异常操作
//需要开始调用到Realm中
System.out.println("========================================");
System.out.println("1、进入认证方法");
subject.login(token);
System.out.println("登录完成");
} catch (Exception e) {
map.put("tip","error");
return map;
}
map.put("tip","success");
return map;
}

如果解决了你的问题,请劳驾给个推荐,谢谢!

SSM集成shiro 致使Controller无法自动注册service的更多相关文章

  1. ssm整合shiro—实现认证和授权

    1.简述 1.1    Apache Shiro是Java的一个安全框架.是一个相对简单的框架,主要功能有认证.授权.加密.会话管理.与Web集成.缓存等. 1.2   Shiro不会去维护用户.维护 ...

  2. Spring Bean自动注册的实现方案

    这里Spring管理的Bean,可以认为是一个个的Service,每个Service都是一个服务接口 自动注册Service的好处: 1.根据指定的name/id获取对应的Service,实现简单工厂 ...

  3. 在ASP.NET Core中使用托管启动(hosting startup)程序集,实现批量注册service

    在启动ASPNET Core时可以从外部程序集向应用添加增强功能.例如,外部库可以用托管启动( hosting startup) 实现为应用程序提供附加配置(Configuration)或服务(ser ...

  4. 十一、Spring Boot 集成Shiro和CAS

    1.Shiro 是什么?怎么用? 2.Cas 是什么?怎么用? 3.最好有spring基础 首先看一下下面这张图: 第一个流程是单纯使用Shiro的流程. 第二个流程是单纯使用Cas的流程. 第三个图 ...

  5. Spring MVC 学习总结(十)——Spring+Spring MVC+MyBatis框架集成(IntelliJ IDEA SSM集成)

    与SSH(Struts/Spring/Hibernate/)一样,Spring+SpringMVC+MyBatis也有一个简称SSM,Spring实现业务对象管理,Spring MVC负责请求的转发和 ...

  6. 4.SSM配置shiro权限管理

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.搭建SSM项目: http://www.cnblogs.com/yysbolg/p/6909021.html ...

  7. 七、spring boot 1.5.4 集成shiro+cas,实现单点登录和权限控制

    1.安装cas-server-3.5.2 官网:https://github.com/apereo/cas/releases/tag/v3.5.2 下载地址:cas-server-3.5.2-rele ...

  8. Spring Boot 集成Shiro和CAS

    Spring Boot 集成Shiro和CAS 标签: springshirocas 2016-01-17 23:03 35765人阅读 评论(22) 收藏 举报  分类: Spring(42)  版 ...

  9. ssm集成redis

    身在一个传统的IT公司,接触的新技术比较少,打算年后跳槽,所以抽空学了一下redis. 简单的redis测试,咱们这边就不讲了,现在主要讲讲ssm集成redis的过程,因为现在项目用的就是ssm的框架 ...

随机推荐

  1. Python stdout

    (1)stdout 与 print 当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+'\n') print 将你需要的内容打 ...

  2. 单链表(C语言实现)

    链表结构: SList.h //-------------------------------------------------------------------------- /* **功能:应 ...

  3. nginx gzip 压缩设置

    mime.types 中包含所有文件的类型,不知道的可以去里面查询 gzip配置的常用参数 gzip on|off;  #是否开启gzip gzip_buffers 32 4K| 16 8K #缓冲( ...

  4. 手撸IoC

    Ioc的实现 可以把IoC模式看作是工厂模式的升华,可以把IoC看作一个大工厂,只不过这个大工厂里要生成的对象都是XML文件中给出定义的,然后利用Java的反射变成,根据XML中给出的类名生成相应的对 ...

  5. 普通java类加入spring容器的四种方式

    今天在自己开发的工具类中使用了spring注入的方式调用了其他类,但是发生的报错,在整理了后今天小结一下. 首先简单介绍下spring容器,spring容器是整个spring框架的核心,通常我们说的s ...

  6. mysql 使用过程中出现问题

    1. mysql_front连接报错,sql执行错误#3167的解决方案 提示:The 'INFORMATION_SCHEMA.SESSION_VARIABLES' feature is disabl ...

  7. jquery中bind,live,delegate,on的区别

    这几种方法都是绑定事件用到的,但是他们之间有些差别 bind(type,[data],fn) 为每个匹配元素的特定事件绑定事件处理函数 例如: <ul> <a href=" ...

  8. spring boot: 在maven中装入springframework框架

    1.在maven 的pom.xml中加入 <dependency> <groupId>org.springframework</groupId> <artif ...

  9. python函数的参数匹配

    版本:一般用python2.7.6 python3.4.3会标注 1.不可变对象(整数.字符串)通过对象引用进行传递,在函数内部不可改变. >>> def f(a): ... a=1 ...

  10. 关于unity3D的GL图像库的使用

    GL图象库 GL图象库是底层的图象库,主要功能是使用程序来绘制常见的2D与3D几何图形.这些图形具有一定的特殊性,他们不属于3D网格图形,只会以面的形式渲染.使用GL图象库,可在屏幕中绘制2D几何图形 ...