后端代码
@Controller
@CrossOrigin
@RequestMapping("/VerifyCode")
public class VerifyCodeController {
final int width = 400;
final int height = 200;
final String imgType = "jpeg";
@GetMapping("/GetCode")
public void getcode(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
ServletOutputStream outputStream = response.getOutputStream();
String url = request.getRequestURI();
System.out.println("Hello"+url);
String code = GraphicsHelper.create(width, height, imgType, outputStream);
session.setAttribute(url,code);
System.out.println("验证码为"+session.getAttribute(url));
}
}
```Java
public class GraphicsHelper {
public static String create(final int width, final int height, final String imgType, OutputStream output ){
StringBuffer sb = new StringBuffer();
Random random = new Random();
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.fillRect(0,0,width,height);
Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,
Color.CYAN };
// 在 "画板"上生成干扰线条 ( 50 是线条个数)
for (int i = 0; i < 50; i++) {
graphic.setColor(colors[random.nextInt(colors.length)]);
final int x = random.nextInt(width);
final int y = random.nextInt(height);
final int w = random.nextInt(20);
final int h = random.nextInt(20);
final int signA = random.nextBoolean() ? 1 : -1;
final int signB = random.nextBoolean() ? 1 : -1;
graphic.drawLine(x, y, x + w * signA, y + h * signB);
}
// 在 "画板"上绘制字母
graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
for (int i = 0; i < 6; i++) {
final int temp = random.nextInt(26) + 97;
String s = String.valueOf((char) temp);
sb.append(s);
graphic.setColor(colors[random.nextInt(colors.length)]);
graphic.drawString(s, i * (width / 6), height - (height / 3));
}
graphic.dispose();
try {
ImageIO.write(image, imgType, output);
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
前端代码
<template>
<div>
<input type="text" name="" ref="val" id="">
<input type="button" @click="refush()">
<img ref="code" src="http://localhost:8888/web/VerifyCode/GetCode">
</div>
</template>
<script>
var socket;
export default {
name: "chat",
data(){
return{
}
},beforeMount() {
if(typeof WebSocket == undefined){
return console.log("您的浏览器不支持Websocket")
}
else{
socket = new WebSocket("ws://localhost:8010");
}
}
,methods:{
refush(){
this.$refs.code.src="http://localhost:8888/web/VerifyCode/GetCode?time="+new Date();
var ajax = new XMLHttpRequest();
ajax.open("get","http://localhost:8888/web/VerifyCode/GetCode")
ajax.send();
},
}
}
</script>
<style scoped>
</style>