package jspImageServlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class getImg extends HttpServlet {
private Font mFont=new Font("宋体",Font.PLAIN,12);
/**
* Constructor of the object.
*/
public getImg() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s="";
int intCount=0;
intCount=(new Random()).nextInt(9999);
if(intCount<1000) intCount+=1000;
s=intCount+"";
HttpSession session=request.getSession(true);
session.setAttribute("getImg", s);
response.setContentType("image/gif");
ServletOutputStream out=response.getOutputStream();
BufferedImage image=new BufferedImage(35,14,BufferedImage.TYPE_INT_RGB);
Graphics gra=image.getGraphics();
gra.setColor(Color.yellow);
gra.fillRect(1,1,33,12);
gra.setColor(Color.black);
gra.setFont(mFont);
char c;
for(int i=0;i<4;i++) {
c=s.charAt(i);
gra.drawString(c+"",i*7+4,11);
}
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
在 Jsp 页面<img src="<url-pattern>URL</url-pattern>"> 调用