@RequestMapping(value="/123.html")
public void yaz(HttpServletResponse response,HttpServletRequest request) throws Exception{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("text/html;charset=utf-8");
int width=80;int height=40;
//畫板
BufferedImage b =new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//工具
Graphics g= b.getGraphics();
g.setColor(new Color(40, 200, 255));
g.fillRect(0, 0, width, height);
char[] ch="QWERTYUIOPASDFGHJKLZXCVBNM1234567890".toCharArray();
Random random = new Random();
int len = ch.length,index;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
index = random.nextInt(len);
g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
g.setFont(new Font("微軟雅黑", Font.BOLD, 18));
g.drawString(ch[index]+"", i*15+3, 18);
sb.append(ch[index]);
}
//干擾線
for(int i=1;i<10000;i++){
g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
g.drawLine(random.nextInt(i*3+2), random.nextInt(i*5+1), random.nextInt(i*3+1),random.nextInt(i*9));
}
//結束
g.dispose();
b.flush();
//保存
request.getSession().setAttribute("yzm", sb.toString());
try {
//輸出圖片到頁面
ImageIO.write(b, "png", response.getOutputStream());
} catch (IOException e) {
}
}
前台頁面怎麼用?
<body>
<!-- 圖片的路徑直接是驗證碼的請求路徑即可 -->
<img alt="" src="<%=request.getContextPath()%>/123.html" id="reload" onclick="reload2()">
<script type="text/javascript">
function reload2(){
var time = new Date().getTime();
document.getElementById("reload").src="<%=request.getContextPath()%>/123.html?d="+time;
}
//為什麼請求多了一個參數呢? 是為了告訴浏覽器這是一個不同的請求,否則驗證碼不刷新
</script>
</body>