vue+SSM實現(xiàn)驗證碼功能
源碼:https://github.com/HannahLihui/StudentManager-SSM/tree/master/SSM-git/StudentManager-SSM-master
1.前端有一個img引入,這里this.src=this.src+'?'就會調用映射到后臺的checkCode
<el-form-item prop="code">
<img src="checkCode" alt="" width="100" height="32" class="passcode" style="height:43px;cursor:pointer; float:left;"onclick="this.src=this.src+'?'">>
<el-input v-model="login.code" placeholder="請輸入驗證碼" style="width: 100px; float:center" auto-complete="off"></el-input>
</el-form-item>
2.后臺返回一個圖片
@RequestMapping(value="/checkCode")
public void checkCode(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設置相應類型,告訴瀏覽器輸出的內容為圖片
response.setContentType("image/jpeg");
HttpSession session = request.getSession();
//設置響應頭信息,告訴瀏覽器不要緩存此內容
response.setHeader("pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", );
RandomValidateCode randomValidateCode = new RandomValidateCode();
try {
randomValidateCode.getRandcode(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
3.是通過RandomValidateCode生成隨機字符串以及圖片。下面這個代碼可以直接用一下。來自:
http://www.dbjr.com.cn/article/152255.htm
public class RandomValidateCode {
public static final String RANDOMCODEKEY = "randomcode_key";//放到session中的key
private Random random = new Random();
private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產生的字符串
private int width = 80;//圖片寬
private int height = 26;//圖片高
private int lineSize = 40;//干擾線數(shù)量
private int stringNum = 4;//隨機產生字符數(shù)量
/**
* 生成隨機圖片
*/
public void getRandcode(HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession();
//BufferedImage類是具有緩沖區(qū)的Image類,Image類是用于描述圖像信息的類
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
//產生Image對象的Graphics對象,改對象可以在圖像上進行各種繪制操作
Graphics g = image.getGraphics();
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
g.setColor(getRandColor(160, 200));
//繪制干擾線
for(int i=0;i<=lineSize;i++){
drowLine(g);
}
//繪制隨機字符
String randomString = "";
for(int i=1;i<=stringNum;i++){
randomString=drowString(g,randomString,i);
}
session.removeAttribute(RANDOMCODEKEY);
session.setAttribute(RANDOMCODEKEY, randomString);
g.dispose();
try {
//將內存中的圖片通過流動形式輸出到客戶端
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 獲得字體
*/
private Font getFont(){
return new Font("Fixedsys",Font.CENTER_BASELINE,18);
}
/*
* 獲得顏色
*/
private Color getRandColor(int fc,int bc){
if(fc > 255)
fc = 255;
if(bc > 255)
bc = 255;
int r = fc + random.nextInt(bc-fc-16);
int g = fc + random.nextInt(bc-fc-14);
int b = fc + random.nextInt(bc-fc-18);
return new Color(r,g,b);
}
/*
* 繪制字符串
*/
private String drowString(Graphics g,String randomString,int i){
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
randomString +=rand;
g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(rand, 13*i, 16);
return randomString;
}
/*
* 繪制干擾線
*/
private void drowLine(Graphics g){
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x, y, x+xl, y+yl);
}
/*
* 獲取隨機的字符
*/
public String getRandomString(int num){
return String.valueOf(randString.charAt(num));
}
}
--------------------------------------------------------------------------------
4.至于驗證驗證碼就是我弄了半天的東西。。。
因為我不太會vue 然后寫前端研究了會會才知道它是怎么用的。然后我開始是想從前端拿到后端的session,但是vue這個是html頁面,不能<%@ %>引入java代碼,然后我又試了一下js的ajax引入,但是報錯,vue框架我也不太懂。。然后還是交給后端驗證嘛。
然后就很簡單了,從login那里驗證,提交的時候多了一個驗證碼,但是我覺得這樣做其實是不太好的,因為驗證碼跟登錄一起驗證,有點耗時,分開比較好。
submitForm(login) {
this.$refs[login].validate((valid) => {
if (valid) {
this.loadings(); //加載動畫
// window.alert(this.login.code);
this.$http.post('/login', {
username: this.login.username,
password: this.login.password,
remember: this.login.remember,
code:this.login.code
}).then(result => {
//window.alert(result);
// 判斷用戶是否登錄成功,后端返回JSON格式數(shù)據(jù),不然娶不到數(shù)據(jù)
if (result.body.success) {
alert("success");
window.location.href = "/listStudentInfo";
this.loading.close(); //關閉動畫加載
} else {
// 彈出錯誤信息框
this.$emit(
'submit-form',
this.$message({
message:result.body.message,
type: 'warning',
duration: 6000
}),
);
// 清空表單狀態(tài)
this.$refs[login].resetFields();
}
});
}
else {
this.$emit(
'submit-form',
this.$message({
message: '輸入信息有誤!',
type: 'warning',
duration: 6000
}),
);
return false;
}
});
},
@RequestMapping("/login")
public Result Login( @RequestParam(value = "username", required = false) String username,
@RequestParam(value = "password", required = false) String password,
@RequestParam(value = "remember", required = false) String remember,
@RequestParam(value = "code", required = false) String code,
HttpServletRequest request
) {
String error = null;
HttpSession session = request.getSession();
System.out.println(code);
//System.out.println(session.getAttribute( RandomValidateCode.RANDOMCODEKEY));
if(username==null||session.getAttribute( RandomValidateCode.RANDOMCODEKEY).equals(code)) {
//System.out.println("code 有問題");
return new Result(false, error);
}
//System.out.println(password);
//System.out.println("調試");
Subject subject=SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(username,password);
if (remember != null) {
if (remember.equals("true")) {
//說明選擇了記住我
token.setRememberMe(true);
} else {
token.setRememberMe(false);
}
} else {
token.setRememberMe(false);
}
System.out.println(token.isRememberMe());
try {
subject.login(token);
Result re=new Result(true, "success");
return new Result(true,error);
} catch (UnknownAccountException e) {
System.out.println( "登陸出錯");
error = "用戶賬戶不存在,錯誤信息:" + e.getMessage();
}catch (IncorrectCredentialsException ex) {
System.out.println( "用戶名和密碼不匹配");
error = "用戶名或密碼錯誤,錯誤信息:" + ex.getMessage();
}catch (AuthenticationException e) {
System.out.println( "其他的登陸錯誤");
error = "錯誤信息:" + e.getMessage();
}
return new Result(false, error);
}
5.session
簡單說一下我理解的session和cookie的區(qū)別吧,session是保存在服務端的,cookie是保存在客戶端的,就是本地會有一個文件夾專門保存cookie。cookie主要是為了保存用戶狀態(tài)嘛,因為http是無狀態(tài)的連接,每次連接完就不會知道下一次是不是同一個用戶。但是保存用戶信息在很多應用場景中都是必要的。而session比cookie更加安全,因為session信息保存在服務端的,不容易被盜用。所以重要登陸信息還是應該保存在session上。而且服務端能夠保存的session比較大,而單個cookie一般不超過20k.
session是怎么保存用戶信息的呢?就是一個用戶有一個sessionId,通過sessionId保存用戶信息。
session的使用:
session.setAttribute("key","value");
session.getAttribute("key");
6.登陸界面

總結
以上所述是小編給大家介紹的vue+SSM實現(xiàn)驗證碼功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
Vue.directive 實現(xiàn)元素scroll邏輯復用
這篇文章主要介紹了Vue.directive 實現(xiàn)元素scroll邏輯復用功能,文中給大家提到元素實現(xiàn)滾動的條件有兩個,具體內容詳情大家參考下本文2019-11-11
vue-element-admin開發(fā)教程(v4.0.0之后)
由于vue-element-admin的架構再4.0.0版本后做了重構,整體結構上和之前的還是很相似的,但是也有些變化,本文就介紹vue-element-admin開發(fā)教程(v4.0.0之后),感興趣的可以了解一下2022-04-04
vue 自定指令生成uuid滾動監(jiān)聽達到tab表格吸頂效果的代碼
這篇文章主要介紹了vue 自定指令生成uuid滾動監(jiān)聽達到tab表格吸頂效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
解決el-select數(shù)據(jù)量過大的3種方案
最近做完一個小的后臺管理系統(tǒng),快上線了,發(fā)現(xiàn)一個問題,有2個select的選項框線上的數(shù)據(jù)量是1w+,而測試環(huán)境都是幾百的,所以導致頁面直接卡住了,本文給大家總結了3種方法,需要的朋友可以參考下2023-09-09

