//ImageServlet package com.muke; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ImageServlet extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{ BufferedImage bi= new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB); Graphics g=bi.getGraphics(); Color c = new Color(200,150,255); g.setColor(c); g.fillRect(0, 0, 68, 22); //验证码里面内容字母数字组合 char[] ch ="ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789".toCharArray(); Random r =new Random(); int len=ch.length,index; StringBuffer sb=new StringBuffer(); for(int i=0;i<4;i++){ index=r.nextInt(len); g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255))); //随机产生颜色 g.drawString(ch[index]+"", (i*15)+3, 18); sb.append(ch[index]); } request.getSession().setAttribute("piccde", sb.toString()); ImageIO.write(bi,"JPG",response.getOutputStream()); } } //web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>ImageServlet</servlet-name> <servlet-class>com.muke.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ImageServlet</servlet-name> <url-pattern>/servlet/ImageServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
填入路径代码的时候,不要学视频里面手打,要学会复制
<url-pattern>/servlet/ImageServlet</url-pattern>这里打错了,应该和<servlet-class>com.muke.ImageServlet</servlet-class>对应