1)开始遇到一个问题,所有的action怎么都拦截不住,似乎spring security失效了,然后在所有的action前面加上“/”之后,在数据库资源里也是类似于/***.action就好了,这样的话就没有问题了。我个人觉得有个不错的解决方式,就是不同角色可访问的jsp建立不用的包,然后struts2配置文件里用不同的package,不用的包作为不同的命名空间,这样也比较清晰,然后在页面所有的action前加上相应的包名,这样拦截起来就更方便了,在数据库的资源表里只要配置/admin/**, /user/**等等就好。其实呢,spring security的这种拦截方式是request拦截,是ss默认的拦截方式,如果想使用forward拦截,记得在web.xml中进行配置如下:
<filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping>
不过一般情况下用对request拦截最好,原因很简单,就不用说了。
2)第二个就是从登陆页面往后台传参数的问题了,就是要在登录时多加几个参数时,默认的AuthenticationProcessFilter既不支持保存额外参数,也没有提供扩展点来实现这个功能,实际上就算是Spring Security-3.x中也因为只能配置一个handler,实际扩展时还是比较麻烦。所以这个时候一般的选择就是自定义过滤器了。为此我们要扩展AuthenticationProcessFilter,这里可以写一个loginFilter继承AuthenticationProcessFilter,实际上我们只需要重写attemptAuthentication()这个方法,先调用super.attemptAuthentication()获得生成的Authentication,如果这部分没有抛出异常,我们下面再去从request中获得mark参数,再把这个参数保存到session里。最后返回authentication对象即可。
转一段:
常见的问题就是要在登录时多加几个参数时,默认的AuthenticationProcessFilter既不支持保存额外参数,也没有提供扩展点来实现这个功能,实际上就算是Spring Security-3.x中也因为只能配置一个handler,实际扩展时还是比较麻烦。所以这个时候一般的选择就是自定义过滤器了。
我们的目标是在登录时除了填写用户名和密码之外,再添加一个mark参数。
我们的目的是在登录时将这个参数保存到session中,以备后用。为此我们要扩展AuthenticationProcessFilter:
public class LoginFilter extends AuthenticationProcessingFilter { public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException { Authentication authentication = super.attemptAuthentication(request); String mark = request.getParameter("mark"); request.getSession().setAttribute("mark", "mark"); return authentication; } }
实际上我们只需要重写attemptAuthentication()这个方法,先调用super.attemptAuthentication()获得生成的Authentication,如果这部分没有抛出异常,我们下面再去从request中获得mark参数,再把这个参数保存到session里。最后返回authentication对象即可。
下面修改配置文件,在xml中添加一个名为loginFilter的bean,使用custom-filter将它加入到过滤器链中,放到原来的form-login的前面。
<beans:bean id="loginFilter" class="com.family168.springsecuritybook.ch211.LoginFilter"> <custom-filter before="AUTHENTICATION_PROCESSING_FILTER" /> <beans:property name="authenticationManager" ref="_authenticationManager"/> <beans:property name="defaultTargetUrl" value="/"/> </beans:bean>
这样我们自定义的LoginFilter就会取代原本的AuthenticationProcessFilter处理用户登录,并在用户登录成功时将额外的mark参数保存到session中。
之后在jsp中,我们就可以直接通过${sessionScope['mark']}来获得mark的参数值。