源码: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", 0);
RandomValidateCode randomValidateCode = new RandomValidateCode();
try {
randomValidateCode.getRandcode(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
3.是通过RandomValidateCode生成随机字符串以及图片。下面这个代码可以直接用一下。来自博客:
https://blog.csdn.net/weidong_y/article/details/80630383
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;//干扰线数量
private int stringNum = 4;//随机产生字符数量
/**
* 生成随机图片
*/
public void getRandcode(HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession();
//BufferedImage类是具有缓冲区的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格式数据,不然娶不到数据
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
}),
);
// 清空表单状态
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的区别吧,session是保存在服务端的,cookie是保存在客户端的,就是本地会有一个文件夹专门保存cookie。cookie主要是为了保存用户状态嘛,因为http是无状态的连接,每次连接完就不会知道下一次是不是同一个用户。但是保存用户信息在很多应用场景中都是必要的。而session比cookie更加安全,因为session信息保存在服务端的,不容易被盗用。所以重要登陆信息还是应该保存在session上。而且服务端能够保存的session比较大,而单个cookie一般不超过20k.
session是怎么保存用户信息的呢?就是一个用户有一个sessionId,通过sessionId保存用户信息。
session的使用:
session.setAttribute("key","value");
session.getAttribute("key");