1.首先引入HuTool的依賴包
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.8</version>
</dependency>
2.登入頁面
<div class="layui-form-item input-item" id="imgCode">
<label for="code">驗證碼</label>
<input type="text" placeholder="請輸入驗證碼" name="code" autocomplete="off" id="code" class="layui-input">
<img th:src="@{/login/getCode}" onclick="this.src=this.src+'?'">
</div>
3.LoginController.java 登入控制器
package com.wang.springboot.sys.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.wang.springboot.sys.common.ActiveUser;
import com.wang.springboot.sys.common.ResultObj;
import com.wang.springboot.sys.common.WebUtils;
import com.wang.springboot.sys.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;
/**
* @author 王一甯
* @since 2019-11-21
*/
@RestController
@RequestMapping("/login")
public class LoginController {
@RequestMapping("/login")
public ResultObj login(String loginname, String pwd, String code,HttpSession session){
//獲得存儲在session中的驗證碼
String sessionCheckCode = (String) session.getAttribute("code");
//判斷驗證碼是否正确
if (code!=null && sessionCheckCode.equals(code)){
//登入成功,傳回json的提示。
return ResultObj.LOGIN_SUCCESS;
}else {
//登陸失敗,提示驗證碼不正确!
return ResultObj.LOGIN_CHECKCODE_ERROR_PASS;
}
}
/**
* 得到登陸驗證碼
* @param response
* @param session
* @throws
*/
@RequestMapping("/getCode")
public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
//HuTool定義圖形驗證碼的長和寬,驗證碼的位數,幹擾線的條數
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,10);
//将驗證碼放入session
session.setAttribute("code",lineCaptcha.getCode());
try {
ServletOutputStream outputStream = response.getOutputStream();
lineCaptcha.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}