服务器响应图像的生成

服务器响应的生成:HTTP响应报头——HttpServletResponse接口的应用 收藏

一,响应报头 

       响应报头允许服务器传递不能放在状态行中的附加响应信息,以及关于服务器的信息和对Request-URI所标识的资源进行下一步访问的信息   

        常用的响应报头   

                 Location    

                 Content-Type   

                 Referer     

 二,在Servlet中设置HTTP响应报头HttpServletResponse接口

              使用HttpServletResponse的setHeader方法,参数为报头名字和报头的值。  和设置状态代码一样。必须在返回实际的文档之前指定相关的报头。   

              setDateHeader(String headerName,Long 毫秒数):设置含有日期和整数的报头。

              setIntHeader(String header,int headerValue):将int类型的状态代码转换为String插入报头。

              Http容许相同的报头多次出现,上面3中方法将替换任何同名的已有报头。而使 addHeader,addDateHeader和addIntHeader方法添加一个报头。  可以使用containsHeader发发进行检查是否已经设置了特定的报头。

              HttpServletResponse常用的设置报头的方法。  

                       setContentType(String mimeType)方法设置Content-type报头。

                       setContentLength(int length)发发设置Content-length报头,用于浏览器持续性HTTP连接。  

                       addCookie(Cookie c)方法:向set-cookie报头插入一个cookie。  

                      sendRedirect(String url)方法,设置设置状态码和Location报头。

三,构建Excel电子表格 (响应报头Content-type的应用) 

             Excel至少接受3种不同格式的输出:用制表符分隔的数据,HTML表格和本地二进制格式。  使用Content-type响应报头告诉客户程序正在发送电子表格。使用setContentType设置Content-type响应头。Excel表格的MIME类型是application/vnd.ms-excel   

            使用制表符分隔的数据生成电子表格: 

                       response.setContentType(“application/vnd.ms-excel;charset=gb2312”);

                       PrintWriter out = response.getWriter();  

                       输出含有制表符\t的一些数据,不需要输出HTML标签。

四,servlet状态的维持和页面的自动重载。(servlet数据存储方式和Referer响应报头的应用) 

            servlet状态的维持,对于servlet或jsp需要较长时间来处理的请求:   

                      1,跨请求存储数据,维护状态     不专属任意客户的数据,存储在servlet的字段中。     对于用户专属数据,存储在HttpSession对象中。     对于其他servlet或jsp需要用到的数据,存储在ServletContext中。  

                       2,在请求发送给客户程序后,继续进行处理。     启动一个线程响应请求,响应之后自动结束线程。另个线程将继续保持运行处理请求,为保持服务器性能,将继续处理请求的线程优先级调低。  

                       3,在需要较长时间处理的请求处理完后,指示浏览器请求更新。     由于浏览器不维护与服务器之间的连接,服务器需要主动将结果发送给浏览器。     所以使用Referer响应报头,指示浏览器请求更新。

五,使用Servlet生成图像和文字(响应报头Content-Type的应用) 

            (1),把图像文件写入磁盘并提供连接。注意写在您的web服务器目录树下(不是在服务器磁盘的任何地方都行)。  

                       在一些servlet引擎设置中,servlet的目录不能通过web server进入,只能通过servlet引擎。   也就是说您不能通过http:// URL登录,您可以向您的servlet输出的HTML传送IMG标签,或传送HTTP重新定位来让浏览器直接下载图象。    

(CookieDetector (http://www.purpletech.com/code/CookieDetector.html) has an example, with source code, of sending a redirect.)     (CookieDetector (http://www.purpletech.com/code/CookieDetector.html)   有一个例子,有传送重新定位源代码。    图象可以被保存在浏览器的cache中,当再次请求时不必重新运行servlet,因此减轻了服务器的负担。    

                       图象不能从磁盘中删除,因此您必须写一段程序来定期清理图象目录,或进入目录 后用手工删除。(或买一张大点的硬盘)

             (2),用Java 2 JPEGCodec类,或Acme Labs' GIFEncoder类将Java Graphics 转换成图象文件或二进制流。  

                      在<img>的src属性中调用实现上述功能的Servlet并传递相关的参数,如背景图片路径、输出文字、文字输出的位置、字体、大小等,   由该Servlet进行图文处理,并返回处理后的图像数据,从而在网页上显示出加上文字的图像。    这个原理也是实现将数据库中的图像数据显示到网页上所用的原理。

   实现方法:  

        1,设置Content-Type响应报头为“images/jpeg”或“image/gif”或其他图片类型的报头。   

                 使用HttpServletResponse的setContentType方法设置。必须在返回实际的内容之前指定相关的报头。   

         2,获取原始的输出流。  

                 使用ServletResponse接口的getOutputSteam方法。    注意:request的getOutputStream和getWriter不能同时使用 也不能重复调用。前者为输出流后者为打印流! 

         3,获取图片的真实路径,封装为File对象。   

                  使用ServletContext接口的getRealPath方法指定虚拟路径,把虚拟路径映射为真实路径。    File类  

         4,获取二进制文件流。

               图片大多数是二进制数据,所以使用字节输入流读入图片文件的。使用FileInputSteam类。  

          5,创建图片在程序内的缓冲对象:BufferedImage对象。  

                 通过构造函数创建一个BufferedImage对象。给出宽度,高度,以及由BufferedImage类中定义的常量所定义的图像类型。           

                 **可以在BufferedImage上绘制内容。调用图像的getGraphics方法,将得到的Graphics对象转换成Graphics2D,使用Graphics2D 来进行绘画操作。    

             6,对图片进行解编输入码输出处理的二种方法。      

                 【1】,使用专门的API处理jpg图片或gif图片:读入文件解码输入,放入BufferedImage缓冲对象后编码输出。   

                       JPG和GIF图片文件可以使用com.sun.image.codec.jpeg.JPEGImageDecoder类和Acme Labs的GIFEncoder类。

                     对输入流数据进行解码后输入       

                             JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(二进制文件流)方法 返回将读入的二进制文件流按jpg图片格式进行解码的解码器对象。 

                      图片缓冲对象临时存储解码图片      

                              BufferedImage image = decoder.decodeAsBufferedImage()方法将解码后的图片放入BufferedImage缓冲对象中。                  

                      对输出流数据进行编码后输出       

                             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(输出流)方法 返回 jpg格式图片的编码器对象。

                       对输出流进行编码器的封装。       

                             encoder.encode(BufferedImage缓冲对象),将BufferedImage缓冲对象进行编码后让输出流输出。 

view plaincopy to clipboardprint?
package com.qu.servlet.responseHeaders.contentType;  
 
 
 
 
 
import java.awt.Color;  
 
import java.awt.Font;  
 
import java.awt.Graphics;  
 
 
 
import java.awt.image.*;  
 
import java.io.File;  
 
import java.io.FileInputStream;  
 
import java.io.IOException;  
 
import java.io.InputStream;  
 
import javax.servlet.ServletConfig;  
 
import javax.servlet.ServletException;  
 
import javax.servlet.ServletOutputStream;  
 
import javax.servlet.http.HttpServlet;  
 
import javax.servlet.http.HttpServletRequest;  
 
import javax.servlet.http.HttpServletResponse;  
 
 
 
import com.sun.image.codec.jpeg.*;  
 
 
 
public class JpegImageServlet extends HttpServlet {  
 
      
 
    private String text = "";               //要嵌的文字  
 
    private String imagePath = "";          //被嵌的图片的虚拟路径  
 
    private int x = 0;                      //坐标  
 
    private int y = 0;  
 
    private String fontColor = "";          //字体颜色  
 
    private int fontSize = 0;               //字体大小  
 
    private String fontStyle = "";          //字体风格(斜体,粗体等)  
 
    private String fontName = "";           //字体名称  
 
    private String realPath;                //图片绝对路径  
 
       
 
    public JpegImageServlet() {  
 
        super();  
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.GenericServlet#destroy() 
 
     */ 
 
    @Override 
 
    public void destroy() {  
 
        super.destroy();  
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig) 
 
     */ 
 
    @Override 
 
    public void init(ServletConfig config) throws ServletException {  
 
        System.out.println("11111111111");  
 
        text = this.getStrParameter(config,"text","");  
 
        imagePath = this.getStrParameter(config,"imagePath","");  
 
        x = this.getIntParameter(config,"x",0);  
 
        y = this.getIntParameter(config,"y",0);  
 
        fontColor = this.getStrParameter(config,"fontColor","");  
 
        fontSize = this.getIntParameter(config,"fontSize",16);  
 
        fontStyle = this.getStrParameter(config,"fontStyle","'");  
 
        fontName = this.getStrParameter(config,"fontName","");  
 
        realPath = config.getServletContext().getRealPath(imagePath);  
 
         
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
 
     */ 
 
    @Override 
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  
 
            throws ServletException, IOException {  
 
        /*请求处理*/ 
 
        request.setCharacterEncoding("gb2312");  
 
          
 
        /*响应处理*/ 
 
        response.setContentType("image/jpeg; charset=gb2312");  
 
          
 
        ServletOutputStream output = response.getOutputStream();  
 
          
 
        File imageFile = new File(realPath);  
 
        InputStream input = new FileInputStream(imageFile);  
 
      
 
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(input);  
 
        BufferedImage bufimg = decoder.decodeAsBufferedImage();  
 
        /**/ 
 
        Graphics g = bufimg.createGraphics();  
 
      
 
        g.setColor(Color.white);//设置颜色  
 
        Font mFont = new Font(fontName,Font.PLAIN,fontSize);//设置字体为默认字体  
 
        if(fontStyle.equalsIgnoreCase("italic")) {  
 
            mFont=new Font(fontName,Font.ITALIC,fontSize);  
 
        }  
 
        if(fontStyle.equalsIgnoreCase("bold")) {  
 
            mFont=new Font(fontName,Font.BOLD,fontSize);  
 
        }  
 
        if(fontStyle.equalsIgnoreCase("plain")){   
 
            mFont=new Font(fontName,Font.PLAIN,fontSize);  
 
        }  
 
        g.setFont(mFont);   
 
        g.drawString(text,x,y);//输出文字  
 
         
 
       System.out.println("33333");  
 
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);  
 
        encoder.encode(bufimg);  
 
 
 
        input.close();  
 
        output.close();  
 
          
 
          
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
 
     */ 
 
    @Override 
 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
 
            throws ServletException, IOException {  
 
        this.doGet(req, resp);  
 
    }  
 
      
 
    public String getStrParameter(ServletConfig config, String parameter, String defaultValue){  
 
        String paraValue = config.getInitParameter(parameter);  
 
          
 
        if (paraValue != null && !paraValue.equals("")){  
 
            //需要的话将参数值转码  
 
        }else{  
 
            paraValue = defaultValue;  
 
        }  
 
        return paraValue;  
 
    }  
 
      
 
    public int getIntParameter(ServletConfig config, String parameter, int defaultValue){  
 
        int paraValue;  
 
        String temp = config.getInitParameter(parameter);  
 
          
 
        if (temp != null && !temp.equals("")){  
 
            paraValue = Integer.parseInt(temp);  
 
        }else{  
 
            paraValue = defaultValue;  
 
        }  
 
          
 
        return paraValue;  
 
    }  
 

package com.qu.servlet.responseHeaders.contentType;

 

 

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

 

import java.awt.image.*;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.sun.image.codec.jpeg.*;

 

public class JpegImageServlet extends HttpServlet {

 

 private String text = "";               //要嵌的文字

 private String imagePath = "";          //被嵌的图片的虚拟路径

 private int x = 0;                      //坐标

 private int y = 0;

 private String fontColor = "";          //字体颜色

 private int fontSize = 0;               //字体大小

 private String fontStyle = "";          //字体风格(斜体,粗体等)

 private String fontName = "";           //字体名称

 private String realPath;    //图片绝对路径

 

 public JpegImageServlet() {

  super();

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.GenericServlet#destroy()

  */

 @Override

 public void destroy() {

  super.destroy();

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)

  */

 @Override

 public void init(ServletConfig config) throws ServletException {

  System.out.println("11111111111");

  text = this.getStrParameter(config,"text","");

     imagePath = this.getStrParameter(config,"imagePath","");

        x = this.getIntParameter(config,"x",0);

        y = this.getIntParameter(config,"y",0);

        fontColor = this.getStrParameter(config,"fontColor","");

        fontSize = this.getIntParameter(config,"fontSize",16);

        fontStyle = this.getStrParameter(config,"fontStyle","'");

        fontName = this.getStrParameter(config,"fontName","");

        realPath = config.getServletContext().getRealPath(imagePath);

      

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

  */

 @Override

 protected void doGet(HttpServletRequest request, HttpServletResponse response)

   throws ServletException, IOException {

  /*请求处理*/

  request.setCharacterEncoding("gb2312");

  

        /*响应处理*/

  response.setContentType("image/jpeg; charset=gb2312");

  

  ServletOutputStream output = response.getOutputStream();

  

  File imageFile = new File(realPath);

  InputStream input = new FileInputStream(imageFile);

 

  JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(input);

  BufferedImage bufimg = decoder.decodeAsBufferedImage();

  /**/

  Graphics g = bufimg.createGraphics();

 

        g.setColor(Color.white);//设置颜色

        Font mFont = new Font(fontName,Font.PLAIN,fontSize);//设置字体为默认字体

        if(fontStyle.equalsIgnoreCase("italic")) {

         mFont=new Font(fontName,Font.ITALIC,fontSize);

        }

        if(fontStyle.equalsIgnoreCase("bold")) {

         mFont=new Font(fontName,Font.BOLD,fontSize);

        }

        if(fontStyle.equalsIgnoreCase("plain")){

         mFont=new Font(fontName,Font.PLAIN,fontSize);

        }

        g.setFont(mFont);

        g.drawString(text,x,y);//输出文字

      

       System.out.println("33333");

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);

        encoder.encode(bufimg);

 

        input.close();

        output.close();

       

       

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

  */

 @Override

 protected void doPost(HttpServletRequest req, HttpServletResponse resp)

   throws ServletException, IOException {

  this.doGet(req, resp);

 }

 

 public String getStrParameter(ServletConfig config, String parameter, String defaultValue){

  String paraValue = config.getInitParameter(parameter);

  

  if (paraValue != null && !paraValue.equals("")){

   //需要的话将参数值转码

  }else{

   paraValue = defaultValue;

  }

  return paraValue;

 }

 

 public int getIntParameter(ServletConfig config, String parameter, int defaultValue){

  int paraValue;

  String temp = config.getInitParameter(parameter);

  

  if (temp != null && !temp.equals("")){

   paraValue = Integer.parseInt(temp);

  }else{

   paraValue = defaultValue;

  }

  

  return paraValue;

 }

}

           

                   【2】,使用javax.imageio.ImageIO类对响应报头中指定的图片类型进行解编码处理。     使用ImageIO类的write方法,该方法根据不同用途进行了重载。   

                                    使用ImageIO类的Read方法读入一个输入流获得一个BufferedImage对象。

                                    使用ImageIO类的write方法,该方法进行了重载。                                  

                                  使用ImageIO类的write,传递一个BufferedImage缓冲对象(进行了自定义的绘图操作和缓冲了读入的图片),指定一个String的图片格式类型,一个输出流对象。

view plaincopy to clipboardprint?
package com.qu.servlet.responseHeaders.contentType;  
 
 
 
import java.awt.Color;  
 
import java.awt.Font;  
 
import java.awt.Graphics;  
 
import java.awt.image.BufferedImage;  
 
import java.io.File;  
 
import java.io.FileInputStream;  
 
import java.io.IOException;  
 
import javax.imageio.ImageIO;  
 
import javax.servlet.ServletConfig;  
 
import javax.servlet.ServletException;  
 
import javax.servlet.ServletOutputStream;  
 
import javax.servlet.http.HttpServlet;  
 
import javax.servlet.http.HttpServletRequest;  
 
import javax.servlet.http.HttpServletResponse;  
 
 
 
 
 
public class ImageIOServlet extends HttpServlet {  
 
 
 
      
 
    private String text = "";               //要嵌的文字  
 
    private String imagePath = "";          //被嵌的图片的虚拟路径  
 
    private int x = 0;                      //坐标  
 
    private int y = 0;  
 
    private String fontColor = "";          //字体颜色  
 
    private int fontSize = 0;               //字体大小  
 
    private String fontStyle = "";          //字体风格(斜体,粗体等)  
 
    private String fontName = "";           //字体名称  
 
    private String realPath;                //图片绝对路径  
 
       
 
    public ImageIOServlet() {  
 
        super();  
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.GenericServlet#destroy() 
 
     */ 
 
    @Override 
 
    public void destroy() {  
 
        super.destroy();  
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig) 
 
     */ 
 
    @Override 
 
      
 
    public void init(ServletConfig config) throws ServletException {  
 
        System.out.println("11111111111");  
 
        text = this.getStrParameter(config,"text","");  
 
        imagePath = this.getStrParameter(config,"imagePath","");  
 
        x = this.getIntParameter(config,"x",0);  
 
        y = this.getIntParameter(config,"y",0);  
 
        fontColor = this.getStrParameter(config,"fontColor","");  
 
        fontSize = this.getIntParameter(config,"fontSize",16);  
 
        fontStyle = this.getStrParameter(config,"fontStyle","'");  
 
        fontName = this.getStrParameter(config,"fontName","");  
 
        realPath = config.getServletContext().getRealPath(imagePath);  
 
       System.out.println(realPath);  
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
 
     */ 
 
    @Override 
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  
 
            throws ServletException, IOException {  
 
        /*请求处理*/ 
 
        request.setCharacterEncoding("gb2312");  
 
            
 
        /*响应处理*/ 
 
        response.setContentType("image/gif; charset=gb2312");  
 
          
 
        ServletOutputStream output = response.getOutputStream();  
 
          
 
        File imageFile = new File(realPath);  
 
          
 
        FileInputStream imgInput = new FileInputStream(imageFile);  
 
          
 
        //Image img = ImageIO.read(imgInput);  
 
          
 
        BufferedImage bimg = ImageIO.read(imgInput);  
 
        /**/ 
 
        Graphics g = bimg.getGraphics();  
 
          
 
        g.setColor(Color.red);//设置颜色  
 
        Font mFont = new Font(fontName,Font.PLAIN,fontSize);//设置字体为默认字体  
 
        if(fontStyle.equalsIgnoreCase("italic")) {  
 
            mFont=new Font(fontName,Font.ITALIC,fontSize);  
 
        }  
 
        if(fontStyle.equalsIgnoreCase("bold")) {  
 
            mFont=new Font(fontName,Font.BOLD,fontSize);  
 
        }  
 
        if(fontStyle.equalsIgnoreCase("plain")){   
 
            mFont=new Font(fontName,Font.PLAIN,fontSize);  
 
        }  
 
        g.setFont(mFont);   
 
        g.drawString(text,x,y);//输出文字  
 
          
 
        ImageIO.write(bimg, "gif", output);  
 
      
 
        bimg.flush();  
 
        imgInput.close();  
 
        output.close();  
 
          
 
    }  
 
 
 
    /* (non-Javadoc) 
 
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
 
     */ 
 
    @Override 
 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
 
            throws ServletException, IOException {  
 
        this.doGet(req, resp);  
 
    }  
 
      
 
    public String getStrParameter(ServletConfig config, String parameter, String defaultValue){  
 
        String paraValue = config.getInitParameter(parameter);  
 
          
 
        if (paraValue != null && !paraValue.equals("")){  
 
            //需要的话将参数值转码  
 
        }else{  
 
            paraValue = defaultValue;  
 
        }  
 
        return paraValue;  
 
    }  
 
      
 
    public int getIntParameter(ServletConfig config, String parameter, int defaultValue){  
 
        int paraValue;  
 
        String temp = config.getInitParameter(parameter);  
 
          
 
        if (temp != null && !temp.equals("")){  
 
            paraValue = Integer.parseInt(temp);  
 
        }else{  
 
            paraValue = defaultValue;  
 
        }  
 
          
 
        return paraValue;  
 
    }  
 

package com.qu.servlet.responseHeaders.contentType;

 

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import javax.imageio.ImageIO;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

 

public class ImageIOServlet extends HttpServlet {

 

 

 private String text = "";               //要嵌的文字

 private String imagePath = "";          //被嵌的图片的虚拟路径

 private int x = 0;                      //坐标

 private int y = 0;

 private String fontColor = "";          //字体颜色

 private int fontSize = 0;               //字体大小

 private String fontStyle = "";          //字体风格(斜体,粗体等)

 private String fontName = "";           //字体名称

 private String realPath;    //图片绝对路径

 

 public ImageIOServlet() {

  super();

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.GenericServlet#destroy()

  */

 @Override

 public void destroy() {

  super.destroy();

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)

  */

 @Override

 

 public void init(ServletConfig config) throws ServletException {

  System.out.println("11111111111");

  text = this.getStrParameter(config,"text","");

     imagePath = this.getStrParameter(config,"imagePath","");

        x = this.getIntParameter(config,"x",0);

        y = this.getIntParameter(config,"y",0);

        fontColor = this.getStrParameter(config,"fontColor","");

        fontSize = this.getIntParameter(config,"fontSize",16);

        fontStyle = this.getStrParameter(config,"fontStyle","'");

        fontName = this.getStrParameter(config,"fontName","");

        realPath = config.getServletContext().getRealPath(imagePath);

       System.out.println(realPath);

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

  */

 @Override

 protected void doGet(HttpServletRequest request, HttpServletResponse response)

   throws ServletException, IOException {

  /*请求处理*/

  request.setCharacterEncoding("gb2312");

   

        /*响应处理*/

  response.setContentType("image/gif; charset=gb2312");

  

  ServletOutputStream output = response.getOutputStream();

  

  File imageFile = new File(realPath);

  

  FileInputStream imgInput = new FileInputStream(imageFile);

  

  //Image img = ImageIO.read(imgInput);

  

  BufferedImage bimg = ImageIO.read(imgInput);

  /**/

  Graphics g = bimg.getGraphics();

  

        g.setColor(Color.red);//设置颜色

        Font mFont = new Font(fontName,Font.PLAIN,fontSize);//设置字体为默认字体

        if(fontStyle.equalsIgnoreCase("italic")) {

         mFont=new Font(fontName,Font.ITALIC,fontSize);

        }

        if(fontStyle.equalsIgnoreCase("bold")) {

         mFont=new Font(fontName,Font.BOLD,fontSize);

        }

        if(fontStyle.equalsIgnoreCase("plain")){

         mFont=new Font(fontName,Font.PLAIN,fontSize);

        }

        g.setFont(mFont);

        g.drawString(text,x,y);//输出文字

       

        ImageIO.write(bimg, "gif", output);

   

        bimg.flush();

        imgInput.close();

        output.close();

       

 }

 

 /* (non-Javadoc)

  * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

  */

 @Override

 protected void doPost(HttpServletRequest req, HttpServletResponse resp)

   throws ServletException, IOException {

  this.doGet(req, resp);

 }

 

 public String getStrParameter(ServletConfig config, String parameter, String defaultValue){

  String paraValue = config.getInitParameter(parameter);

  

  if (paraValue != null && !paraValue.equals("")){

   //需要的话将参数值转码

  }else{

   paraValue = defaultValue;

  }

  return paraValue;

 }

 

 public int getIntParameter(ServletConfig config, String parameter, int defaultValue){

  int paraValue;

  String temp = config.getInitParameter(parameter);

  

  if (temp != null && !temp.equals("")){

   paraValue = Integer.parseInt(temp);

  }else{

   paraValue = defaultValue;

  }

  

  return paraValue;

 }

}

  

                     【3】,不使用解码和编码来处理输入流和输出流。直接BufferedOutputStream输出缓冲流,输出BufferedImage缓冲对象。 

view plaincopy to clipboardprint?
response.setContentType("images/jpeg"); //设置响应报头       
 
 
 
OutputStream output = response.getOutputStream();//得到输出流       
 
 
 
ServletContext context = getServletContext();//得到上下文对象       
 
 
 
InputStream imageIn=context.getResourceAsStream(imagePath);//文件流           
 
 
 
BufferedInputStream bis=new BufferedInputStream(imageIn);//使用输入流初始化输入缓冲流。      
 
 
 
 BufferedOutputStream bos=new BufferedOutputStream(output);//使用输出流构造输出缓冲流。       
 
 
 
byte data[]=new byte[4096];//缓冲字节数        
 
 
 
int size= bis.read(data); //初始化读入       
 
 
 
while (size!=-1)        
 
 
 
{           
 
 
 
              bos.write(data,0,size);//输出读入的字节数数据        
 
 
 
              size=bis.read(data);//读取字节数数据       
 
 
 
}//end while        
 
 
 
bis.close();//关闭输入缓冲流        
 
 
 
bos.flush();//清空输出缓冲流                
 
 
 
bos.close();         
 
 
 
output.close();//关闭输出流 

response.setContentType("images/jpeg"); //设置响应报头    

 

OutputStream output = response.getOutputStream();//得到输出流    

 

ServletContext context = getServletContext();//得到上下文对象    

 

InputStream imageIn=context.getResourceAsStream(imagePath);//文件流        

 

BufferedInputStream bis=new BufferedInputStream(imageIn);//使用输入流初始化输入缓冲流。   

 

 BufferedOutputStream bos=new BufferedOutputStream(output);//使用输出流构造输出缓冲流。    

 

byte data[]=new byte[4096];//缓冲字节数     

 

int size= bis.read(data); //初始化读入    

 

while (size!=-1)     

 

{        

 

              bos.write(data,0,size);//输出读入的字节数数据     

 

              size=bis.read(data);//读取字节数数据    

 

}//end while     

 

bis.close();//关闭输入缓冲流     

 

bos.flush();//清空输出缓冲流             

 

bos.close();      

 

output.close();//关闭输出流

  

WEB.XML

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?> 
 
<web-app version="2.4"   
 
    xmlns="http://java.sun.com/xml/ns/j2ee"   
 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 
 
  <welcome-file-list> 
 
    <welcome-file>imageIO</welcome-file> 
 
  </welcome-file-list> 
 
  <!-- Servlet start --> 
 
  <servlet> 
 
    <servlet-name>ExcelServlet</servlet-name> 
 
    <servlet-class>com.qu.servlet.responseHeaders.contentType.ExcelServlet</servlet-class> 
 
  </servlet> 
 
  <servlet> 
 
    <servlet-name>JpegImageServlet</servlet-name> 
 
    <servlet-class>com.qu.servlet.responseHeaders.contentType.JpegImageServlet</servlet-class> 
 
    <init-param> 
 
        <param-name>text</param-name> 
 
        <param-value>新闻</param-value> 
 
    </init-param> 
 
    <init-param> 
 
        <param-name>imagePath</param-name> 
 
        <param-value>/images/bg.jpg</param-value> 
 
    </init-param> 
 
    <init-param>    
 
        <param-name>x</param-name> 
 
        <param-value>20</param-value>    
 
    </init-param>       
 
    <init-param>    
 
        <param-name>y</param-name> 
 
        <param-value>20</param-value>    
 
    </init-param>       
 
    <init-param> 
 
        <param-name>fontColor</param-name> 
 
        <param-value>red</param-value> 
 
    </init-param>   
 
    <init-param>    
 
        <param-name>fontSize</param-name> 
 
        <param-value>16</param-value> 
 
    </init-param> 
 
    <init-param>    
 
        <param-name>fontStyle</param-name> 
 
        <param-value>bold</param-value> 
 
    </init-param> 
 
    <init-param>    
 
        <param-name>fontName</param-name> 
 
        <param-value>宋体</param-value>                 
 
    </init-param> 
 
  </servlet> 
 
  <servlet> 
 
    <servlet-name>ImageIOServlet</servlet-name> 
 
    <servlet-class>com.qu.servlet.responseHeaders.contentType.ImageIOServlet</servlet-class> 
 
    <init-param> 
 
        <param-name>text</param-name> 
 
        <param-value>漫画美女!</param-value> 
 
    </init-param> 
 
    <init-param> 
 
        <param-name>imagePath</param-name> 
 
        <param-value>/images/MM.gif</param-value> 
 
    </init-param> 
 
    <init-param>    
 
        <param-name>x</param-name> 
 
        <param-value>50</param-value>    
 
    </init-param>       
 
    <init-param>    
 
        <param-name>y</param-name> 
 
        <param-value>30</param-value>    
 
    </init-param>       
 
    <init-param> 
 
        <param-name>fontColor</param-name> 
 
        <param-value>black</param-value> 
 
    </init-param>   
 
    <init-param>    
 
        <param-name>fontSize</param-name> 
 
        <param-value>20</param-value> 
 
    </init-param> 
 
    <init-param>    
 
        <param-name>fontStyle</param-name> 
 
        <param-value>bold</param-value> 
 
    </init-param> 
 
    <init-param>    
 
        <param-name>fontName</param-name> 
 
        <param-value>隶书</param-value>                 
 
    </init-param>   
 
  </servlet> 
 
  <!-- servlet end --> 
 
  <!-- servlet mapping start --> 
 
  <servlet-mapping> 
 
    <servlet-name>ExcelServlet</servlet-name> 
 
    <url-pattern>/excel</url-pattern> 
 
  </servlet-mapping> 
 
  <servlet-mapping> 
 
    <servlet-name>JpegImageServlet</servlet-name> 
 
    <url-pattern>/jpegImage</url-pattern> 
 
  </servlet-mapping> 
 
  <servlet-mapping> 
 
    <servlet-name>ImageIOServlet</servlet-name> 
 
    <url-pattern>/imageIO</url-pattern> 
 
  </servlet-mapping> 
 
  <!-- servlet mapping end --> 
 
</web-app> 


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/qfs_v/archive/2008/06/20/2567609.aspx

你可能感兴趣的:(应用服务器,Web,浏览器,servlet,Excel)