servlet部分:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse
/**
* Servlet implementation class RandomPassword
*/
@WebServlet("/rp.do")
public class RandomPassword extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RandomPassword() {
super();
// TODO Auto-generated constructor stub
}
protected void processRequest(HttpServletRequest request,HttpServletResponse response)throws Exception{
response.setContentType("image/jpeg"); //设置页面输出格式
BufferedImage bi=new BufferedImage(100,80,BufferedImage.TYPE_INT_RGB);
Graphics2D g=bi.createGraphics();
StringBuilder sb=new StringBuilder(); //创建验证码字符串
for(int i=0;i<4;i++){
sb.append((int)(Math.random()*9)); //将随机验证码加入字符串
}
request.getSession().setAttribute("random", sb.toString()); //将验证码保存,以便以后验证
g.fillRect(0, 0, 100, 80); //设置绘制区域(默认颜色为白色)
Font font=new Font("宋体",Font.BOLD,30); //设置字体格式
g.setFont(font);
g.setColor(Color.black);
g.drawString(sb.toString(), 20, 40);
ImageIO.write(bi, "jpeg", response.getOutputStream()); //输出验证码图片
response.getOutputStream().flush();
response.getOutputStream().close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
processRequest(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
processRequest(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Html部分:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="pass.do">
![](rp.do) //设置验证码路径
输入图片上的密码:<input type="text" name="password" value=""/>
<button>提交</button>
</form>
</body>
</html>