java鬼混笔记:shiro 7、shiro验证码功能

来源:互联网 发布:文言虚词乎的用法 编辑:程序博客网 时间:2024/06/05 13:29

这次的笔记是shiro验证码功能,上一篇笔记没有做,这一篇笔记继续做。

完整的项目下载路径(项目下载网上的hui框架来着,什么鬼文件都在里面,暂清除,所以很多):

http://download.csdn.net/download/u013845177/9992748

相关的lib包路径:

http://download.csdn.net/download/u013845177/9992728


就上一篇的自定义认证表单LSFormAuthenticationFilter.java类进行修改。

LSFormAuthenticationFilter.java中修改如下:

package cn.common;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import org.apache.shiro.session.Session;import org.apache.shiro.subject.Subject;import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;// 自定义登录表单认证public class LSFormAuthenticationFilter extends FormAuthenticationFilter {@Overrideprotected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue)throws Exception {<!-- 验证码功能开始 -->// 1、ICodeC.java中生成一个验证码后,会放到session中,这个就是session中保存的验证码String iCode = (String) ((HttpServletRequest)request).getSession().getAttribute("iCode");// 页面传过来的验证码String code = request.getParameter("code");if(iCode != null && code != null) {if(!iCode.equals(code)){// 2、两码不一样// 3、shiroLoginFailure是shiro自带的参数key,这里设置认证出错信息request.setAttribute("shiroLoginFailure", "codeError");// 4、这个在loginC.java中的Login()方法中可以获取得到,如果获取的shiroLoginFailure=codeError,说明是验证码出错,并做判断处理, 上一篇有说明// 5、拒绝访问,不往用户和密码认证那里处理了,直接返回。可以在自定义的LSRealm.java中查看doGetAuthenticationInfo()方法,当验证码不正确,方法不执行return true; }}<!-- 验证码功能结束 -->// 6、验证码一致,继续走 用户名和密码认证return super.onAccessDenied(request, response, mappedValue);}}

// 最后在之前登录的LoginC.java中login()方法中加入一个判断,当返回的信息是codeError,就是知道是验证出错了

LoginC.java的login()方法那块代码如下:

@Controllerpublic class LoginC extends ControllerSupport{// 登录页面@RequestMapping("login")public String login(Model model, HttpServletRequest request) {// 设置一个basePath, 这样就可以在jsp页面中直接用户${basePath}获取项目名getSession().setAttribute("basePath", request.getServletContext().getContextPath());// 这是核心String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");if(exceptionClassName!=null){if (UnknownAccountException.class.getName().equals(exceptionClassName)) {model.addAttribute("msg", "账号不存在");} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {model.addAttribute("msg", "密码不正确");} else if("codeError".equals(exceptionClassName)){// LSFormAuthenticationFilter.java设置request.setAttribute("shiroLoginFailure", "codeError");model.addAttribute("msg", "认证码不正确");} else {model.addAttribute("msg", "未知错误");}}return "login";}......

ok...验证码就这么多

阅读全文
0 0
原创粉丝点击