---
title: "关于Shiro在Jetty下运行正常，但Tomcat下报错的原因和解决办法"
author: "aixinnature"
date: "2013-06-14T10:22:37Z"
tags: []
categories: ["企业架构"]
slug: "shiro-jetty-tomcat"
draft: false
lastmod: "2013-06-14T10:28:56Z"
id: 1886575
url: "https://sind.iteye.com/blog/1886575"
---

文章开始之前先扯点闲的，相比Spring Security 的强大复杂，  Shiro是个简洁扩展性强易用的轻量级安全框架，源代码的思路也很清晰。如果你觉得安全框架都太过通用无法满足您的特殊需求，想构建公司内部的安全框架，那么参考shiro的实现也是个不错的思路。

      项目运行环境：mac os 10.x ，maven3.0， eclipse ，jetty7.5,
      相关框架：spring3.x,shiro2.1
      
      问题描述：由于eclipse下的jetty插件配合maven非常方便测试，所以编写代码都是用jetty做服务器跑的，但打包好war以后在tomcat下跑，总会报shiro的一个错误

> 
> [color=red]org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton.  This is an invalid application configuration.[/color] 
>         at org.apache.shiro.SecurityUtils.getSecurityManager(SecurityUtils.java:123) 
>         at org.apache.shiro.subject.Subject$Builder.<init>(Subject.java:627) 
>         ... 
> 


   在网络上找到很多关于shiro报错的文章，大多情况都是spring中的shiro上下文配置错误，如果是这种错误那么在jetty下一样会报错。仔细查看错误代码会发现所有的shiro报错都跟jsp里的shiro tag标签有关，而且这些页面都是公用页面，如common.jsp,header.jsp等的。

尝试过很多办法，如拷贝jstl.jar到tomcat的lib包下，去除不兼容的servlet.jar包等等，问题依旧没有解决
最终在shiro的官方论坛中找到答案，传送门：
http://shiro-user.582556.n2.nabble.com/Do-you-have-to-SecurityUtils-setSecurityManager-in-a-web-app-to-use-shiro-tag-library-td7114798.html

      出错原因：

> Tomcat invokes the filter chain only on REQUEST dispatcher. It's a standard servlet thing, but I'm not sure if Jetty implements dispatchers at all or they just have a different default
> （Tomcat调用filter过滤器是默认只拦截 REQUEST请求，这其实是符合servlet标准的，但jetty调用filter过滤器时会拦截所有请求） 
> 例如我们的common.jsp被别的页面用<jsp:include>标签包含时，jetty下filter依然起作用，但tomcat可不理会，这样common.jsp里如果有shiro的jsp标签，这个标签会调用securityManager获取当前的用户对象，但由于shirofilter过滤器没起作用，会导致标签找不到上下文
> 

    
     解决办法：
   
> <!-- Shiro Security 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>
> [color=blue]
> 		<dispatcher>REQUEST</dispatcher> 
> 		<dispatcher>FORWARD</dispatcher> 
> 		<dispatcher>INCLUDE</dispatcher> 
> 		<dispatcher>ERROR</dispatcher> [/color]
> 	</filter-mapping>

    
    将蓝色的文字添加到现有shiroFilter 里面就可以了，大致意思是强制这个过滤器过滤所有相关的请求