web get请求获取图片
<div class="p2"><img id="imgId" src="/get/code"><a href="#">看不清,换一张</a>
</div>
后台代码:
/*获取动态验证码*/
@ResponseBody
@RequestMapping(value = "/get/code", method = {RequestMethod.POST, RequestMethod.GET})
public void getCode(HttpServletResponse response) {creatImg(response);
}
private void creatImg(HttpServletResponse response) {int width = 120;int height = 30;// 在内存中生成图片BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 先获取画笔对象Graphics2D g = (Graphics2D) image.getGraphics();// 设置灰色g.setColor(Color.GRAY);// 画填充的矩形g.fillRect(0, 0, width, height);// 设置颜色g.setColor(Color.BLUE);// 画边框g.drawRect(0, 0, width - 1, height - 1);// 准备数据,随机获取4个字符String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";// 设置颜色g.setColor(Color.white);// 设置字体g.setFont(new Font("隶书", Font.BOLD, 20));String code = "";//构造存储字符的数组char[] a = {};//构造存储字符串的集合List<String> list = new ArrayList<String>();Random random = new Random();int x = 20;int y = 20;for (int i = 0; i < 4; i++) {// void rotate(double theta, double x, double y)// theta 弧度// hudu = jiaodu * Math.PI / 180;// 获取正负30之间的角度int jiaodu = random.nextInt(60) - 30;double hudu = jiaodu * Math.PI / 180;g.rotate(hudu, x, y);// 获取下标int index = random.nextInt(words.length());// 返回指定下标位置的字符,随机获取下标char ch = words.charAt(index);//将字符存入字符数组中char[] chc = {ch};//使用字符数组构造字符串String string = new String(chc);//将构造好的字符串添加进list集合中list.add(string);// 写字符串g.drawString("" + ch, x, y);g.rotate(-hudu, x, y);x += 20;}for (int i = 0; i < list.size(); i++) {code += list.get(i);}//将验证码存入上下文中servletContext.setAttribute("code", code);// 设置颜色g.setColor(Color.GREEN);int x1, x2, y1, y2;// 画干扰线for (int i = 0; i < 4; i++) {x1 = random.nextInt(width);y1 = random.nextInt(height);x2 = random.nextInt(width);y2 = random.nextInt(height);g.drawLine(x1, y1, x2, y2);}// 输出到客户端try {ImageIO.write(image, "jpg", response.getOutputStream());} catch (IOException e) {e.printStackTrace();}}
登录验证:
@RequestMapping(value = "/user/login", method = {RequestMethod.POST, RequestMethod.GET})public void Login(@RequestBody UserBean userBean, HttpSession session, HttpServletResponse response) throws Exception {String code = userBean.getCode();//从上下文获取存储的验证码String code1 = (String) servletContext.getAttribute("code");//账号密码为admin.且验证码(忽略大小写)输入正确,则跳转到登陆成功页面if ("".equals(code) || code == null || !code.equalsIgnoreCase(code1)) {HttpServletResponseUtil.back(response, 202, "验证码错误!", null);return;}QueryWrapper<UserBean> queryWrapper = new QueryWrapper<>();queryWrapper.eq("username", userBean.getUsername());queryWrapper.eq("password", userBean.getPassword());List<UserBean> beans = mapper.selectList(queryWrapper);if (beans != null && beans.size() > 0) {log.info("登陆成功,用户名:" + userBean.getUsername());log.info("登陆成功,密码:" + userBean.getPassword());session.setAttribute("loginUser", userBean);HttpServletResponseUtil.back(response, 200, "登录成功!", null);} else {HttpServletResponseUtil.back(response, -1, "账号密码错误", null);}}