web前端学习笔记二(登录界面)
添加验证码
逻辑思路:
后端:
1.生成验证码图片和验证码文本,将验证码文本存入session,返回验证码图片给前端。
2.前端传入用户填写的验证码,后端取出session中的验证码,进行对比。
前端:
1.显示后端返回的验证码图片。
2.获取用户输入的验证码,并提交给后端。
后端实现:
1.编写一个生成验证码的工具类,该工具类能生成验证码图片和验证码文本
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
//生成验证码
public class VerifyCode {
private int width = 100;// 生成验证码图片的宽度
private int height = 30;// 生成验证码图片的高度
private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" };
private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
private Random random = new Random();
private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private String text;// 记录随机字符串
/**
* 获取一个随意颜色
*
* @return
*/
private Color randomColor() {
int red = random.nextInt(150);
int green = random.nextInt(150);
int blue = random.nextInt(150);
return new Color(red, green, blue);
}
/**
* 获取一个随机字体
*
* @return
*/
private Font randomFont() {
String name = fontNames[random.nextInt(fontNames.length)];
int style = random.nextInt(4);
int size = random.nextInt(5) + 24;
return new Font(name, style, size);
}
/**
* 获取一个随机字符
*
* @return
*/
private char randomChar() {
return codes.charAt(random.nextInt(codes.length()));
}
/**
* 创建一个空白的BufferedImage对象
*
* @return
*/
private BufferedImage createImage() {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setColor(bgColor);// 设置验证码图片的背景颜色
g2.fillRect(0, 0, width, height);
return image;
}
public BufferedImage getImage() {
BufferedImage image = createImage();
Graphics2D g2 = (Graphics2D) image.getGraphics();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
String s = randomChar() + "";
sb.append(s);
g2.setColor(randomColor());
g2.setFont(randomFont());
float x = i * width * 1.0f / 4;
g2.drawString(s, x, height - 8);
}
this.text = sb.toString();
drawLine(image);
return image;
}
/**
* 绘制干扰线
*
* @param image
*/
private void drawLine(BufferedImage image) {
Graphics2D g2 = (Graphics2D) image.getGraphics();
int num = 5;
for (int i = 0; i < num; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
g2.setColor(randomColor());
g2.setStroke(new BasicStroke(1.5f));
g2.drawLine(x1, y1, x2, y2);
}
}
public String getText() {
return text;
}
public static void output(BufferedImage image, OutputStream out) throws IOException {
ImageIO.write(image, "JPEG", out);
}
}
2.把验证码图片返回前端,把验证码文本存入session,这个方法写在登录的controller类里
@RequestMapping("/verifyCode")
public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
VerifyCode verifyCode = new VerifyCode();//调用生成验证码工具类
BufferedImage image = verifyCode.getImage();//获得验证码图片到流中
String text = verifyCode.getText();//获取验证码文本
session.setAttribute("verify_code",text);//把文本存入session中,用于与前端返回进行比较
verifyCode.output(image,response.getOutputStream());//把图片返回前端
}
3.把前端传入的验证码和session里的验证码对比。这里的Result类是我自定义的一个信息类。这个方法依然是写在登录的controller类中
@RequestMapping("/verifyUser")
public Result verifyUser(HttpServletRequest request, String verifyCode, String username, String password){
String text = (String)request.getSession().getAttribute("verify_code");//获取session里的验证码
if (verifyCode==null||!verifyCode.toLowerCase().equals(text.toLowerCase())){//与前端传来的验证码比对
return new Result(400,"验证码错误!");
}else {
User user = userService.verifyUser(username,password);
if(user==null){
return new Result(401,"用户名或密码错误!");
}else{
request.getSession().setAttribute("user",user);
return new Result(200,"OK");
}
}
}
自定义的Result类
/*
定义返回类
status = 200,代表成功
status = 400,代表错误
status = 401,代表身份未验证
*/
public class Result {
private int status;
private String info;
public Result(int status,String info){
this.status=status;
this.info=info;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
到此,后端任务完成
前端实现:
1.以图片方式显示验证码图片,img:的写法代表后面的src地址来源动态可变
<img :src="vrcUrl" id="verifyCode" @click="updateVerifyCode">
2.在data(){}里面添加vrcUrl。url后面加一个时间参数,是为了点击更换验证码。如果不加,你点击后,系统会任务url地址没变,不会去请求新的,就不会更换验证码图片了
vrcUrl:'http://localhost:8081/verifyCode?time='+new Date(),//验证码获取地址,添加一个时间,触发事件时系统就发现变量改变,从而更换地址
3.编写一个方法,点击图片可以更换验证码
methods: {
updateVerifyCode(){
this.vrcUrl='http://localhost:8081/verifyCode?time='+new Date();
},
}
4.在登录方法里加入验证码,如果登录失败,要自动刷新一次验证码
login() {
const _this = this
this.axios.defaults.withCredentials=true //开启发送cookie
this.axios({
method:'post',
url:"http://localhost:8081/verifyUser",
params:{'verifyCode': _this.verifyCode,'username': _this.username,'password':_this.password}
}).then(function (resp) {
if(resp.data.status==400){
alert(resp.data.info)
_this.vrcUrl='http://localhost:8081/verifyCode?time='+new Date();
}else{
if(resp.data.status==200){
_this.$store.commit('login',resp.data)
_this.$router.replace('/home')
}else{
alert(resp.data.info)
_this.vrcUrl='http://localhost:8081/verifyCode?time='+new Date();
}
}
})
},