图片显示不了呀
login.jsp里的代码:
<img class="tpyzm" src="<%=request.getContextPath()%>/ImageServlet" alt="验证码" />
<a class="can" href="javascript:reloadCode();">刷新</a>
然后ImageServlet.java里的代码
/**
* Project Name:zjweb
* File Name:ImageServlet.java
* Package Name:com.zjweb.action
* Date:2016年10月31日上午11:09:33
*/
package com.zjweb.action;
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;
/**
* ClassName: ImageServlet <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON(可选). <br/>
* date: 2016年10月31日 上午11:09:33 <br/>
*
* @author haoshasha
* @version
* @since JDK 1.8
*/
public class ImageServlet extends HttpServlet
{
/**
*
* doGet:(用来生成图片验证码的). <br/>
* TODO(这里描述这个方法适用条件 – 可选).<br/>
* @author haoshasha
* @param request
* @param response
* @throws IOException
* @since JDK 1.8
*/
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 = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890".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("piccode", sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());
}
}
web.xml里的代码
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.zjweb.action.ImageServlet </servlet-class>
</servlet>
<!-- 映射关系访问到servlet类 -->
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/servlet/ImageServlet</url-pattern>
</servlet-mapping>