//获取
@RequestMapping("yzm")
public void yzm(HttpServletRequest re,HttpServletResponse po) throws IOException{
int height=45;
int width=80;
BufferedImage buff=new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);
Graphics gr=buff.getGraphics();
gr.setColor(Color.white);
//字体样式,加粗,大小
gr.setFont(new Font("微软雅黑",Font.BOLD,18));
gr.fillRect(0, 0, width, height);//制定矩形
String zm="0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
StringBuffer sb=new StringBuffer();
Random r=new Random();
for(int i=0;i<4;i++){
int index=(int) (Math.random()*zm.length());
Color c=new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(255));
gr.setColor(c);
char zms=zm.charAt(index);
//设置每个字符验证码的位置 x,y
gr.drawString(""+zms,i*(width/4),(height/2)+5);
sb.append(zms);
}
System.out.println(sb.toString());
// 将四位数字的验证码保存到Session中,用于验证。
HttpSession session=re.getSession();
session.setAttribute("code", sb.toString());
// 禁止图像缓存。
/* po.setHeader("Pragma", "no-cache");
po.setHeader("Cache-Control", "no-cache");
po.setDateHeader("Expires", 0);
po.setContentType("image/jpeg;charset=utf-8"); */
for(int i=0;i<12;i++){
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
gr.setColor(c);
gr.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
// 将图像输出到Servlet输出流中。
ServletOutputStream sos = po.getOutputStream();
ImageIO.write(buff, "jpeg",sos);
sos.close();
}
}
<pre name="code" class="java"> @RequestMapping("code")
public void code(HttpServletRequest re,HttpServletResponse po) throws UnsupportedEncodingException{
HttpSession session=re.getSession();
String code=(String) session.getAttribute("code");
System.out.println("session获取:"+code);
po.addCookie(new Cookie("code",code));
//解决中文乱码问题
po.addCookie(new Cookie("code1", URLEncoder.encode("张三", "UTF-8")));
Cookie[] cookies = re.getCookies();
String cookieName="";
String codes="";
Integer maxage=0;
for (Cookie cookie : cookies)
{
if(cookie.getName().equals("code1")){
cookieName = URLDecoder.decode(cookie.getValue(), "UTF-8");
}
if(cookie.getName().equals("code")){
//值获取
codes=cookie.getValue();
//设置,获取时间
maxage=cookie.getMaxAge();
}
}
System.out.println(cookieName);
System.out.println(codes);
System.out.println(maxage);
}