ResponseServlet.java:
@WebServlet("/responseServlet")
public class ResponseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//創建圖片對象
int width = 100;
int height= 50;
BufferedImage image =new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//創建畫筆對象
Graphics g =image.getGraphics();
//填充背景色
g.setColor(Color.PINK);
g.fillRect(0,0,width,height);
//畫邊框
g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,height-1);
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成隨機角標
Random ran = new Random();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//獲取隨機字符
char ch = str.charAt(index);
//寫驗證碼
g.drawString(ch+"",width/5*i,height/2);
}
//畫干擾線
g.setColor(Color.GREEN);
//隨機生成座標點
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//將圖片寫入resp
ImageIO.write(image,"JPG",resp.getOutputStream());
}
}
html寫法:
<body>
<img id ="checkImage" src="/Response/responseServlet">
<a id="change" href="#">看不清,換一張</a>
</body>
<script>
window.onload=function () {
var checkImage = document.getElementById("checkImage");
var change = document.getElementById("change");
var check = function () {
var time = new Date().getTime();
checkImage.src = "/Response/responseServlet?"+time;
};
checkImage.onclick = check;
change.onclick = check;
}
</script>
效果圖: