Controller类中主要方法:
<span style="font-size:12px;">/** * 获取验证码图片和文本(验证码文本会保存在HttpSession中) */ @RequestMapping("/getVerifyCodeImage") public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException { //设置页面不缓存 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_ALL_MIXED, 4, null); //将验证码放到HttpSession里面 request.getSession().setAttribute("verifyCode", verifyCode); System.out.println("本次生成的验证码为[" + verifyCode + "],已存放到HttpSession中"); //设置输出的内容的类型为JPEG图像 response.setContentType("image/jpeg"); BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 25, 4, true, Color.WHITE, Color.BLACK, null); //写给浏览器 ImageIO.write(bufferedImage, "JPEG", response.getOutputStream()); } /** * @param request * @return * 登录验证 */ @RequestMapping("/toLogin") public String toLogin(HttpServletRequest request) { String username = request.getParameter("username"); String password = request.getParameter("password"); //返回地址 String returnUrl="/login"; //User user =userService.queryUserByUserName(username); //获取HttpSession验证码 String verifyCode =(String) request.getSession().getAttribute("verifyCode"); //获取用户输入的验证码 String submitCode = WebUtils.getCleanParam(request,"verifyCode"); System.out.println("用户输入的验证码是:"+submitCode+";系统生成的验证码是:"+verifyCode); if(StringUtils.isEmpty(submitCode)|| !StringUtils.equalsIgnoreCase(verifyCode, submitCode)) { request.setAttribute("login_msg","验证码错误" ); return returnUrl; } //根据获取的用户名和密码封装成Token UsernamePasswordToken token =new UsernamePasswordToken(username,password); //是否记住用户 token.setRememberMe(true); //获取当前的subject Subject subject =SecurityUtils.getSubject(); try { System.out.println("对用户:["+username+"]进行登录验证,验证开始..."); //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查 //每个Realm都能在必要时对提交的AuthenticationTokens作出反应 //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法 subject.login(token); System.out.println("对用户:["+username+"]进行登录验证,验证通过!"); returnUrl="/main"; }catch (UnknownAccountException e) { System.out.println("对用户:["+username+"]进行登录验证,验证未通过!错误:未知账号"); request.setAttribute("login_msg","未知账号"); }catch (IncorrectCredentialsException e) { System.out.println("对用户:["+username+"]进行登录验证,验证未通过!错误:密码错误"); request.setAttribute("login_msg", "密码错误"); }catch (LockedAccountException e) { System.out.println("对用户:["+username+"]进行登录验证,验证未通过!错误:账号被锁定"); request.setAttribute("login_msg", "账号被锁定"); }catch (ExcessiveAttemptsException e) { System.out.println("对用户:["+username+"]进行登录验证,验证未通过!错误:错误次数过多"); request.setAttribute("login_msg", "密码或用户名输入错误次数过多"); }catch (AuthenticationException e) { System.out.println("对用户:["+username+"]进行登录验证,验证未通过!错误:用户名或密码不正确"); request.setAttribute("login_msg", "身份认证失败,用户名或密码不正确"); } //验证是否登录成功 if(subject.isAuthenticated()) { System.out.println("用户:["+username+"]进行登录验证通过"); }else { token.clear(); } return returnUrl; }</span>
jsp页面 login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page isELIgnored="false"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; request.setAttribute("home", path); %> <!DOCTYPE HTML> <html lang="en-US"> <!-- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> --> <script type="text/javascript" src="<%=request.getContextPath()%>/res/login/prefixfree.min.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/res/js/jquery-1.11.3.min.js"></script> <head> <meta charset="UTF-8"> <title>用户登录</title> <link rel="stylesheet" href="<%=request.getContextPath()%>/res/login/login.css" type="text/css"></link> <script type="text/javascript"> var home ="${home}"; var msg ="${login_msg }"; $(function(){ //生成验证码 $('#verifyCodeImage').click(function () { $(this).hide().attr('src', '<%=path%>/member/getVerifyCodeImage?' + Math.floor(Math.random()*100) ).fadeIn(); }); }); window.onbeforeunload = function(){ //关闭窗口时自动退出 if(event.clientX>360&&event.clientY<0||event.altKey){ alert(parent.document.location); } }; function changeCode() { //刷新 $('#verifyCodeImage').hide().attr('src', '<%=path%>/member/getVerifyCodeImage?' + Math.floor(Math.random()*100) ).fadeIn(); event.cancelBubble=true; } if(msg!="") { alert(msg); } </script> </head> <body> <div class="content"> <form action="<%=request.getContextPath()%>/member/toLogin" method="post" class="login-form"> <div class="username"> <input type="text" name="username" placeholder="[email protected]" autocomplete="on" /> <div id="loginMsg"></div> <span class="user-icon icon">u</span> </div> <div class="password"> <input type="password" name="password" placeholder="*******" /> <span class="password-icon icon">p</span> </div> <div class="code-div"> <input type="text" name="verifyCode" placeholder="请输入验证码" /> <img id="verifyCodeImage" src="<%=request.getContextPath()%>/member/getVerifyCodeImage"/> <!-- <a href="javascript:void(0)" onclick="changeCode()">看不清?换一张</a> --> </div> <div class="account-control"> <input type="checkbox" name="rememberMe" id="Remember me" value="Remember me" checked="checked" /> <label for="Remember me" data-on="c" class="check"></label> <label for="Remember me" class="info">Remember me</label> <!-- <input type="hidden" name="rememberMe" value="true"> --> <button type="submit">Login</button> </div> <p class="not-registered">Not a registered user yet?<a>Sign up now!</a></p> </form> </div> </body> </html>
来源:http://blog.csdn.net/jadyer/article/details/12185725
main方法小测试一下