sevlet显示图片

上次讲了servlet起步,这次我写了一个用servlet显示图片的例子。

首先,我们新建一个ImageServlet类。
package servlet.test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageServlet extends HttpServlet {
        
        //显示gif图片
	private static final String gif = "image/gif;charset=GB2312";
        //显示jpeg图片
	private static final String jpg = "image/jpeg;charset=GB2312";

	public ImageServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
                //我這里是相对路径,请根据自己实际情况调整。
		String imagePath = "/img/b1.jpg";
                //获得输出流
		OutputStream stream = response.getOutputStream();
		if (imagePath.toLowerCase().endsWith("jpg")) {
                        //设置contentType,平时用的都是“html/text”
			response.setContentType(jpg);
                        //获得image文件的绝对路径
			imagePath = getServletContext().getRealPath(imagePath);
			InputStream in = new FileInputStream(new File(imagePath));
			//下面将文件编码
                        JPEGImageDecoder decoder = JPEGCodec
					.createJPEGDecoder(in);
			BufferedImage buffer = decoder.decodeAsBufferedImage();
			JPEGImageEncoder encoder =   JPEGCodec.createJPEGEncoder(stream);
			encoder.encode(buffer);
			in.close();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public void init() throws ServletException {

	}
}



其次,设置web.xml,添加以下代码
 <servlet>
  <servlet-name>image</servlet-name>
//这里的servlet-class根据自己的实际情况设定
  <servlet-class>servlet.test.ImageServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>image</servlet-name>
  <url-pattern>/image</url-pattern>
 </servlet-mapping>


最后:测试,将工程部署到tomcat,并启动tomcat,输入:http://localhost:8080/你的工程名/image 。

好了,今天就写到这里,以后有时间再写,希望对大家有帮助,我也是个新手。

你可能感兴趣的:(java,tomcat,Web,servlet,sun)