使用后端生成圖片驗證碼流文件(不推薦)


代碼:

@Controller
@RequestMapping("/user")
public class UserLoginController {

	//生成驗證碼圖片流、並把驗證碼寫到會話中
    @RequestMapping("/loginVerCodeImg")
    public void verifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        response.setHeader("Pragma", "No-cache"); 
        response.setHeader("Cache-Control", "no-cache"); 
        response.setDateHeader("Expires", 0); 
        response.setContentType("image/jpeg"); 
           
        //生成隨機字串 
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 

        //存入會話session 
        HttpSession session = request.getSession(true); 
        //刪除以前的
        session.removeAttribute("verCode");
        session.setAttribute("verCode", verifyCode); 
        //生成圖片 
        int w = 100, h = 30; 
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); 
        
        logger.warn("【loginVerCodeImg】: 生成隨機驗證碼:" + verifyCode);
    }
	
	//登錄方法
    @RequestMapping("/login/addlogin")
    public ModelAndView addlogin(HttpServletRequest request,HttpServletResponse response,Map<String, Object> map){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String verifyCode = request.getParameter("verifyCode");
        request.getSession().setAttribute("username", username);
        //讀取session中verCode的值
        HttpSession session = request.getSession();
        String verCode2 = session.getAttribute("verCode").toString();
        
        if(username == "" || username == null ) {
        	logger.warn("帳戶名為空");
        	map.put("login_msg", "帳戶名為空");
        	return new ModelAndView("/login/login",map);
        }else if (password == "" || password == null) {
        	logger.warn("密碼為空");
        	map.put("username", username);
        	map.put("login_msg", "密碼為空");
        	return new ModelAndView("/login/login",map);
        }else if(!(verifyCode.equals(verCode2) || verifyCode.equals(verCode2.toLowerCase()))) {
        	logger.warn("驗證碼不正確");
        	map.put("username", username);
        	map.put("password", password);
        	map.put("login_msg", "驗證碼錯誤");
    		return new ModelAndView("/login/login",map);
        }
        
        
        logger.warn("【addlogin】:輸入驗證碼:"+ verifyCode + ",session中的驗證碼:"+ verCode2);
        //第1步. 去和數據庫里的數據匹配
        User user = userService.findOneByNameAndPWD(username,password);
        
        if ( user == null){
        	logger.warn("登錄失敗");
        	map.put("username", username);
        	map.put("login_msg", "登錄失敗:帳戶密碼有誤或未啟用的帳戶");
        	return new ModelAndView("/login/login",map);
        }else {
        	
        	//將對象user轉成json格式
        	ObjectMapper mapper = new ObjectMapper();
        	String json;
    		try {
    			json = mapper.writeValueAsString(user);
    		} catch (JsonProcessingException e) {
    			json = null;
    			e.printStackTrace();
    		}

    		//第2步. 設置token至redis
    		String token = session.getId();     
    		redisTemplate.opsForValue().set(String.format("token_%s", token), json, ExpireEnum.REDISExpire.getCode(), TimeUnit.SECONDS);
        	
    		//第3步. 設置token至cookie
    		CookieUtil.set(response, "token", token, ExpireEnum.COOKIEExpire.getCode());
    		return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/userManage/userShow?userid="+user.getUserid()); 	
        }
    }
}

頁面:

<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">  
	<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<#include "../common/header.ftl">
<body>

<div align="left" style="border:100px solid white">
	<div class="container">
	    <div class="row">
	        <div class="col-md-offset-3 col-md-6">
	            <form class="form-horizontal" action="/user/login/addlogin" name="loginfrom" accept-charset="utf-8" method="post">
	            	<div class="form-group">
	                   	
	                	<span class="heading">用戶登錄  </span><font color="red">${(login_msg?if_exists)}</font><p>
	                </div>
	                <div class="form-group">
	                	<label class="control-label control-label-normal">用戶名</label>
	                    <input type="text" class="form-control" id="username" name="username" placeholder="用戶名" value="${username?if_exists}">
	                </div>
	                <div class="form-group">
	                	<label class="control-label control-label-normal">密 碼</label>
	                    <input type="password" class="form-control" id="password" name="password" placeholder="密 碼" value="${password?if_exists}">
	                </div>
	                <div class="form-group">
	                	<label class="control-label control-label-normal">驗證碼</label><p>
	                	<img src="/user/loginVerCodeImg" id="verImg" onclick="javascript:changeImg()" />
	                    <input type="text" class="form-control" id="verifyCode" name="verifyCode" placeholder="驗證碼" />
	                </div>
	                <div class="form-group">
	                    <button type="submit" class="btn btn-default">登錄</button>
	                    <a href="/user/register" class="zcxy" target="_blank">注冊</a><p>
	                </div>
	            </form>
	        </div>
	    </div>
	</div>
</div>
	
</body>
</html>
<!-- 觸發JS刷新-->
 <script type="text/javascript">
    function changeImg(){
        var img = document.getElementById("verImg"); 
        img.src = "/user/loginVerCodeImg?date=" + new Date();;
    }
</script>

  


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com