码迷,mamicode.com
首页 > 其他好文 > 详细

response

时间:2015-03-15 22:56:39      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

web服务器会收到客户端的http请求,会对每一次的请求,分别创建一个用于代表请求的request和代表响应的response对象,获取客户机提交的数据,只需要找request对象;向客户机输出数据,只需找response对象。

 

response常见的应用向客户端输出中文数据:分别以OutputStream和PrintWriter输出

//OutputStream
    public class Demo1 extends HttpServlet {

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

    private void test4(HttpServletResponse response) throws IOException,
            UnsupportedEncodingException {
        
        // 这里把数据写给response,再由response写到浏览器。
        OutputStream out = response.getOutputStream();
        out.write(1);   //编码不一样,去找国标的1代表的字符
        out.write((1 + "").getBytes());   //看到正常的1
    }

    private void test3(HttpServletResponse response) throws IOException,
            UnsupportedEncodingException {
        response.setHeader("Content-type", "text/html,charset=utf-8");
        String data = "中国";

        // 这里把数据写给response,再由response写到浏览器。
        OutputStream out = response.getOutputStream();
        out.write(data.getBytes("utf-8"));
    }

    private void test2(HttpServletResponse response) throws IOException,
            UnsupportedEncodingException {
        // 用html技术中的meta标签模拟一个http响应头,控制浏览器的行为
        String data = "中国";

        // 这里把数据写给response,再由response写到浏览器。
        OutputStream out = response.getOutputStream();
        out.write("<meta http-equiv=‘content-type‘ content=‘text/html;charset=utf-8‘>"
                .getBytes());
        out.write(data.getBytes("utf-8")); // 写成字节流,指定以何种编码写给客户机
    }

    private void test1(HttpServletResponse response) throws IOException,
            UnsupportedEncodingException {
        // 设定浏览器以何种编码打开
        response.setHeader("Content-type", "text/html;charset=utf-8");
        String data = "中国";

        // 这里把数据写给response,再由response写到浏览器。
        OutputStream out = response.getOutputStream();
        out.write(data.getBytes("utf-8")); // 写成字节流,指定以何种编码写给客户机
    }

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

    }
}

 

PrintWriter---writer流只能写,字符或字符串
    public class Demo2 extends HttpServlet {

    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置PrintWrite写给response的码表为utf-8,默认的码表示iso
        response.setCharacterEncoding("UTF-8");
        //设置浏览器的码表
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        String data = "中国";
        PrintWriter out = response.getWriter();
        out.write(data);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }
}

 

 

文件下载:
public class Demo3 extends HttpServlet {

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

        //在servlet里读取资源
        //得到资源的绝对地址
        String path = this.getServletContext().getRealPath("/download/1.jpg");
        //截取文件地址,最后一个斜杠后面的文件名
        String filename = path.substring(path.lastIndexOf("\\") + 1);
        
        //设置以何种方式打开文件
        //下载的图片名为中文的,修改编码
        response.setHeader("content-disposition", "attachement;filename ="  + URLEncoder.encode(filename, "utf-8"));
        response.setHeader("content-disposition", "attachement;filename" + filename);
        InputStream in = null;
        OutputStream out = null;
        
        try{
            in = new FileInputStream(path);
            int len = 0;
            byte buffer[] = new byte[1024];
            out = response.getOutputStream();
            while((len = in.read(buffer)) > 0){
                out.write(buffer, 0, len);
            }
        }finally{
            if(in != null){
                try{
                    in.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }    
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}

 

输出随机图片:
 产生图片:
public class Demo4 extends HttpServlet {

    //输出随机图片
        
        public static final int WIDTH = 120;
        public static final int HEIGHT = 35;
        
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            //内存中构建一幅图像
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            //得到这副图像
            Graphics g = image.getGraphics();
            //设置背景色
            setBackGround(g);
            //设置边框
            setBorder(g);
            //画干扰线
            drawRoundomLine(g);
            //写随机数
            drawRoundomNum((Graphics2D)g);
            //写给浏览器
            response.setContentType("image/jpeg");
            //发头控制浏览器不要缓存
            response.setDateHeader("expries", -1);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragme", "no-cache");
            ImageIO.write(image, "jpg", response.getOutputStream());
        }

        
        private void drawRoundomNum(Graphics2D g) {
            // TODO Auto-generated method stub
            g.setColor(Color.RED);
            g.setFont(new Font("宋体", Font.BOLD, 20));
        
            //汉字的取值区间是 [\u4e00--\u9fa5]
            String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa";
            int x = 10;
            for(int i = 0; i < 5; i ++){
                
                int degree = new Random().nextInt() % 30;  //-30~30    
                String ch = base.charAt(new Random().nextInt(base.length())) + "";
                g.rotate(degree * Math.PI/180, x, 20);//设置旋转角度
                g.drawString(ch, x, 20);  
                g.rotate(-degree * Math.PI/180, x, 20);
                x += 30;
            }
        }


        private void drawRoundomLine(Graphics g) {
            // TODO Auto-generated method stub
            g.setColor(Color.CYAN);
            for(int i = 0; i < 7; i ++){
                int x1= new Random().nextInt(WIDTH);
                int y1= new Random().nextInt(HEIGHT);
                
                int x2= new Random().nextInt(WIDTH);
                int y2= new Random().nextInt(HEIGHT);
            
                g.drawLine(x1, y1, x2, y2);
            }
        }


        private void setBorder(Graphics g) {
            // TODO Auto-generated method stub
            g.setColor(Color.BLUE);
            g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
        }


        private void setBackGround(Graphics g) {
            // TODO Auto-generated method stub
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, WIDTH, HEIGHT);
        }


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

        }

    }

 

在html文件获取此文件,再输出来。

	<html>
	  <head>
	    <title>sign.html</title>
	    <script type="text/javascript">
	    	function changeImage(img){
	    		img.src = img.src + "?" + new Date().getTime();
	    	}
	    </script>
	  </head>
	  
	  <body>
	   	<form>
	   		用户名:<input type="text" name="username"><br/>
	   		密 码:<input type="password" name="password"><br/>
	   		认证码:<input type="text" name="checkcode">
	   		<img src="/day6/servlet/Demo4" onclick="changeImage(this)" alt="换一张" style="cursor:handle">
	   		<input type="submit" value="注册">
	   	</form>
	  </body>
	</html>

  

控制浏览器定时刷新:
public class Demo5 extends HttpServlet {

    //控制浏览器定时刷新
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        test3(request, response);
    }

//实用的跳转
    private void test3(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //假设这是一个处理登录的servlet
        //假设程序运行到此,用户登录成功
        String message = "<meta http-equiv=‘refresh‘ content=‘3;url=/day6/index.jsp‘>等待跳转中,不成功<a href=‘‘>请点击</a>";
        this.getServletContext().setAttribute("message", message);
        this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }
    
    /*private void test2(HttpServletResponse response) throws IOException {
        //假设这是一个处理登录的servlet
        //假设程序运行到此,用户登录成功
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("refresh", "3;url=‘/day6/index.jsp‘");
        response.getWriter().write("等待跳转中,不成功<a href=‘‘>请点击</a>");
    }*/


    //定时产生随机数
    private void test1(HttpServletResponse response) throws IOException {
        response.setHeader("refresh", "3");
        String data = new Random().nextInt(100000) + "";  
        response.getWriter().write(data);
    }

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

    }
    }
message.jsp--显示页面。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘message.jsp‘ starting page</title>
    

  </head>
  
  <body>
    <%
    	String message = (String)application.getAttribute("message");
    	out.write(message);
    %>
  </body>
</html>

  

//控制缓存时间

public class Demo6 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setDateHeader("expires", System.currentTimeMillis() + 1000 * 3600);
        String data = "aaaaaaaaa";
        response.getWriter().write(data);
    }

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

}

 

 

请求重定向:--地址栏发生变化/浏览器会向服务器发送两次意味着有两个response,request
      在用户登录和显示购物车时,通常会用到重定向技术

 

response细节:getOutputStream和getWriter方法分别用于得到输出二进制数据,输出文本数据的ServletOutPutStream,Printwriter对象
getOutputStream和getWriter方法是互斥的,调用其中任何一个方法后,就不能再调用您一个方法。(如果是重定向,就可以在重定向的网页使用与之互斥的方法。否则不可以,因为重定向是重新发起第二次访问)
Servlet程序向ServletOutStream或PrintWriter对象中写入的数据将被Servlet引擎从response里面获取,Sservlet引擎将这些数据当作响应信息的正文。然后再与响应头组合后发送到客户端。
Servlet的service方法结束后,Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果没有,Servlet引擎调用close方法关闭输出流对象

 

response

标签:

原文地址:http://www.cnblogs.com/lcpholdon/p/4340591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!