009-shiro与spring web项目整合【三】验证码、记住我
一、验证码
1、自定义FormAuthenticationFilter
需要在验证账号和名称之前校验验证码
/** * * <p>Title: CustomFormAuthenticationFilter</p> * <p>Description:自定义FormAuthenticationFilter,认证之前实现 验证码校验 </p> * @version 1.0 */ public class CustomFormAuthenticationFilter extends FormAuthenticationFilter { //原FormAuthenticationFilter的认证方法 @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { //在这里进行验证码的校验 //从session获取正确验证码 HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpSession session =httpServletRequest.getSession(); //取出session的验证码(正确的验证码) String validateCode = (String) session.getAttribute("validateCode"); //取出页面的验证码 //输入的验证和session中的验证进行对比 String randomcode = httpServletRequest.getParameter("randomcode"); if(randomcode!=null && validateCode!=null && !randomcode.equals(validateCode)){ //如果校验失败,将验证码错误失败信息,通过shiroLoginFailure设置到request中 httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError"); //拒绝访问,不再校验账号和密码 return true; } return super.onAccessDenied(request, response); } }
2、FormAuthenticationFilter配置
修改applicationContext-shiro.xml中对FormAuthenticationFilter的配置
a、在shiroFilter中添加filters:
<!-- 自定义filter配置 --> <property name="filters"> <map> <!-- 将自定义 的FormAuthenticationFilter注入shiroFilter中 --> <entry key="authc" value-ref="formAuthenticationFilter"/> </map> </property>
b、formAuthenticationFilter定义
<!-- 自定义form认证过虑器 --> <!-- 基于Form表单的身份验证过滤器,不配置将也会注册此过虑器,表单中的用户账号、密码及loginurl将采用默认值,建议配置 --> <bean id="formAuthenticationFilter" class="com.lhx.ssm.shiro.CustomFormAuthenticationFilter"> <!-- 表单中账号的input名称 --> <property name="usernameParam" value="username"/> <!-- 表单中密码的input名称 --> <property name="passwordParam" value="password"/> </bean>
3、登录页面
添加验证码:
<TR> <TD>验证码:</TD> <TD><input id="randomcode" name="randomcode" size="8" /> <img id="randomcode_img" src="${baseurl}validatecode.jsp" alt="" width="56" height="20" align='absMiddle' /> <a href=javascript:randomcode_refresh()>刷新</a></TD> </TR>
4、配置validatecode.jsp匿名访问
修改applicationContext-shiro.xml:
<!-- 验证码,可匿名访问 --> /validatecode.jsp = anon