撰写人——软件二班——陈喜平
需要的工具:tomcat/eclipse/jdk/(注意jdk版本要和tomca相匹配,以及注意区分32位和64位)
步骤:依次创建servlet (服务器需要)/ jsp(页面需要)
引入web.xml
如图所示:
doget方法里面的代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
int width=158;
int height=30;
// 1、首先将画布画出来
BufferedImage buffIMG=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
//创建画笔
Graphics2D g2d=(Graphics2D) buffIMG.getGraphics();
// 画笔颜色
g2d.setColor(Color.white);
// 设置字体
g2d.setFont(new Font("宋体",Font.BOLD,15));
Random rd=new Random();
// 拿到字符串
String word="asdfghjklzxcvbnmqwertyuiop1234567890";
// 3.将字符串画到画布上
int x=25;
int y=25;
for(int i=0;i<4;i++)
{
int index =rd.nextInt(word.length());
char ch = word.charAt(index);
int jiaodu=rd.nextInt(30)-15;
double hudu=jiaodu*Math.PI/180;
g2d.rotate(hudu,x,y);
g2d.drawString(ch+" ", x, y);
x+=9.5;
g2d.rotate(-hudu, x, y);
}
int x1,x2,y1,y2;
for(int j=0;j<3;j++)
{
g2d.setColor(Color.green);
x1=rd.nextInt(width);
x2=rd.nextInt(width);
y1=rd.nextInt(height);
y2=rd.nextInt(height);
g2d.drawLine(x1, y1, x2, y2);
}
// 4.将验证码的图片显示在页面上
ImageIO.write(buffIMG, "jpg", response.getOutputStream());
}
web.xml需要添加的代码
<servlet>
<!-- 服务名 -->
<servlet-name>myservlet</servlet-name>
<!-- 服务名所在的路径 -->
<servlet-class>com.teach.servlet.myservlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- 服务名 -->
<servlet-name>myservlet</servlet-name>
<!-- url请求名-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
全部代码压缩包
链接:https://pan.baidu.com/s/1nApT-Zft4xfzVc5H7rL4Eg
提取码:3bk8
成果图: