JavaWeb 之 HttpServletResponse

1.1:   response,  resquest 对象

   Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象、和代表响应的response对象。

   request和response对象即然代表请求和响应,那我们要获取客户机提交过来的数据,只需要找request对象就行了。

   要向客户机输出数据,只需要找response对象就行了。

   HttpServletResponse对象服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。


1.2    向客户端输出中文数据

两种方式:getOutputStreamgetWriter


方法一:
使用getOutputStream()获得一个Servlet字节流输出数据

实验:getOutputStream().write("中国".getBytes("utf-8"));出现乱码
原因: getBytes()默认为GB2312,这里指定utf-8,而浏览器是以默认的GB2312打开,所以会出现乱码问题


   解决方法:
必须指定浏览器以什么码表解码
1. response.setHeader("content-type", "text/html;charset=utf-8");  //设置请求消息头为utf-8,让浏览器以utf-编码打开
2. <meta http-equiv="" content="">来模拟响应头信息


方法二:getWriter(),获得一个字符输出流

实验:response.getWriter().write("中国");出现乱码
原因:
     因为这里获取到的是字符流,所以服务器在返回给浏览器的时候会转换成字节数据,需要进行编码,这时查的是ISO8859-1码表,ISO8859-1码表
     中没有中文,所以查到的是"??",而服务器是以GB2312打开,GB2312是兼容ISO8859-1的,所以浏览器直接就输出"??"
 
   解决方案:
方式一
response.setHeader("Content-type", "text/html;charset=utf-8");//设置请求消息头为utf-8,让浏览器以utf-编码打开
response.setCharacterEncoding("utf-8");//设置服务器解析时的编码格式为utf-8

方案二
response.setContentType("text/html;charset=utf-8"); 等价于上面两句


建议:
   在使用response.setContentType("text/html;charset=utf-8");的时候加上 
 response.setCharacterEncoding("utf-8");这样更易于阅读


注意:

      getOutputStream和getWriter这两个方法互相排斥,调用了其中的任何一个方法后,就不能再调用另一方法,包括转发时。重定向可以,因为向服务器发送两次请求。

    如果需要同时写入字节或者字符时使用:字节流 getOutputStream( )


示例

package cn.itxushuai;

import java.io.IOException;

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

public class ServletDemo extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//以字节流输出,因为数据的传输都是以字节形式的,所以这里在服务端就不用进行编码
		
		//浏览器端默认为GB2312,
		//getBytes()默认为GB2312
		//response.setCharacterEncoding("utf-8");
		//response.getOutputStream().write("中国".getBytes());

		//以字符流输出,会在服务端进行字节编码
		response.setHeader("Content-type", "text/html;charset=utf-8");//请求浏览器以utf-8打开
		response.setCharacterEncoding("utf-8");//在服务器组织response时,查ISO8859-1码表,浏览器以GB2312打开
		//response.setContentType("text/html;charset=utf-8");//通知浏览器和服务器使用utf-8码表,单独使用即可
		//writer是GB2312,只是服务端出现了问题,是以ISO8859解析
		response.getWriter().write("中国");
		
		//下载的时候指定的编码只能是UTF-8
	}

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

}


1.3  Tip:文件下载和中文(文件名)文件的下载

    利用response将HTTP的响应头"content-disposition"设置为"attachment;filename=xxx"即可实现文件下载功能

   注意:
         如果文件名中包含中文,则文件名要进行URL编码:URLEncoding.encode('卡拉.jpg','utf-8');如果不进行编码则文件名显示错误并且不可下载。

package cn.itxushuai;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

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

public class Demo3Servlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String urlName = URLEncoder.encode("考拉.jpg","utf-8");//当响应给浏览器的文件名为中文时,需要进行URL编码,否则出现乱码
		response.setHeader("content-disposition","attachment;filename="+urlName);
//		response.setHeader("content-disposition","attachment;filename=Koala.jpg");//响应给浏览器时文件名是英文时,可以直接下载
		InputStream in = this.getServletContext().getResourceAsStream("/Koala.jpg");//获取本地文件并封装成流
		OutputStream out = response.getOutputStream();
		
		//文件复制
		int len = 0;
		byte[] buf = new byte[1024];
		while((len=in.read(buf))!=-1){
			out.write(buf,0,len);
		}
		in.close();
	}

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

}


1.4   模拟随机图片产生器

登陆界面源代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>register.html</title>

<script type="text/javascript">

//更新图片
	function changeImg(img){
		
		img.src = img.src+"?"+new Date().getTime();
	}
</script>

</head>
<body>
		<form action="">
		用户名:<input type="text" name="usename"><br/>
		密码:<input type="password" name="password"><br/>
		验证码:<input type="checkbox" name="checknode">
		<img src="/day06/RandomPic" οnclick="changeImg(this)" alt="换一张" style="cusor:hand"><br/>
		<input type="submit" value="注册">
		
		</form>
</body>
</html>



验证码代码

package cn.xushuai;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

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

public class RandomPic extends HttpServlet {
	private static final long serialVersionUID = 1L;
    final int WIDTH =100;
	final int HEIGHT = 27;
		
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
		Graphics graf = image.getGraphics();
		
		//1.设置背景色
			setBackground(graf);
		//2.设置边框
			setBorder(graf);
		//3.画干扰线
			drawRandomLine(graf);
		//4.写随机数
			drawRandomNum((Graphics2D)graf);
		//5.图片写到浏览器
			response.setContentType("image/jpeg");
	
		//刷新按钮的作用:1不管有没有缓存,都像服务端发送请求,2把上次的事情再干一次,
		//告诉浏览器不要缓存
		response.setDateHeader("expries", -1);
		response.setHeader("Cache-Control","no-cache");
		ImageIO.write(image, "jpg", response.getOutputStream());	
	}
	private void setBackground(Graphics graf) {
		graf.setColor(Color.WHITE);
		graf.fillRect(0, 0, WIDTH, HEIGHT);
	}
	private void setBorder(Graphics graf) {
			graf.setColor(Color.BLUE);
		graf.drawRect(1, 1, WIDTH-2, HEIGHT-2);
	}


	private void drawRandomNum(Graphics2D graf) {
				graf.setColor(Color.RED);
		graf.setFont(new Font("宋体",Font.BOLD,15));
		
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\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\	“	
		int x=5;
		for (int i = 0; i < 4; i++) {
			
			int degree = new Random().nextInt()%30;//-30-30
			String ch = base.charAt(new Random().nextInt(base.length()))+"";
			graf.rotate(degree*Math.PI/180,x,20);//设置旋转幅度
			graf.drawString(ch,x,15);
			graf.rotate(-degree*Math.PI/180,x,20);
			x+=25;		
		}		
	}

	private void drawRandomLine(Graphics graf) {
		// TODO Auto-generated method stub
		graf.setColor(Color.GREEN);
		for(int i=0;i<5;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);
			graf.drawLine(x1,y1,x2,y2);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}
}

1.5   发送http头,控制浏览器定时刷新网页(REFRESH)

利用Response设置响应头refresh可以实现页面的定时刷新功能。

refresh头可以被设置为一个整数,实现定是刷新当前页面,也可以在整数后跟分号再在分号后写一个url=指定刷新到的目标URL

response.setHeader("Refresh", "3;url='/news/index.jsp'");

很多网站在提示登录成功后几秒内会跳转到主页,就是由这个功能实现的。

在HTML中用<meta http-equiv= "" content="">可以模拟该刷新头功能

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
		<html>
		  <head>
				<meta http-equiv="Refresh" content="3;url=/day05/index.jsp">
		  </head>
		  <body>
			注册成功,3秒后自动跳转!!
		  </body>
		</html>



package cn.xushuai.exercise;

import java.io.IOException;
import java.util.Random;

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

public class RefreshTest extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

private void test1(HttpServletResponse response) throws IOException {

		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("refresh", "3;url='/day06/index.html'");
		response.getOutputStream().write(
				"恭喜你,登陆成功,本浏览器将在3秒后跳转,如果没有跳转请点:<a href='/day06/index.html'>超链接</a>"
						.getBytes("UTF-8"));
		// response.getWriter().write("登录成功,将在3秒后跳转,如果没有,");//请点<a
		// href=''>超链接</a>");
	}

	// 实用的自动跳转技术(因为数据最终通过jsp输出)
	private void test2(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		//使用HTML的meta标签来控制浏览器的跳转
		String message = "<meta http-equiv='refresh'content='3';url=/day06/index.html'>您好!您已登录成功,本页面将在3秒后跳转如果没有跳转请点<a href=>超链接</a>";
		this.getServletContext().setAttribute("message", message);
		this.getServletContext().getRequestDispatcher("/message.jsp")
				.forward(request, response);
	}
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
				doGet(request, response);
	}
}

1.6   发送http头expires,控制浏览器缓存当前文档内容

1、利用response设置expires响应头为0或-1浏览器就不会缓存当前资源。(同样功能的头还有Cache-Control: no-cache、Pragma: no-cache)

实验:使浏览器每次都重新获取图片
response.setDateHeader("Expires", -1);//设置浏览器不要缓存,不管是转到或者在地址栏里重新输入,都重新去获取资源

2、expires也可以取值为一个时间,指定要缓存到的日期

实验:文件缓存日期检查

response.setDateHeader("Expires", System.currentTimeMillis()+3600*24*1000);

如果使用Expires指定了缓存多长时间的话,新打开一个浏览器会去拿缓存,对于其它的效果一样:刷新会拿重新获取资源,“转到”或者在地址栏里重新输入都会拿缓存


浏览器默认的缓存机制:

如果没有设置Expires头时,只有当刷新或者重新开一个浏览器访问相同资源时才重新获取资源,而“转到”或者在地址栏里输入相同的路径的时候拿的都是缓存。

String data="hello expires";

response.setDateHeader("expires",System.currentTimeMillis()+3600*1000);

response.getWriter().write(data);


1.7   Tip: 通过response实现请求重定向

    1>请求重定向:一个web资源收到客户端请求后,通知客户端去访问另外一个web资源,这称之为请求重定向。

    

    2>重定向特点:

                  a.浏览器会向服务器发送两次请求,意味着有两个resquset,response

                  b.重定向技术,浏览器地址栏会发生变化

    

    3>应用场景:

                用户注册,让用户知道注册成功,重定向到首页。

                购物网站购完后,转到购物车显示页面,用转发按刷新又买一个,所以用重定向。


    4>重定向实现:

            方式一:response.setStatus(302);// 302状态码和location头即可实现重定向

                          response.setHeader("location","/day06/index.jsp");


            方式二:response.sendRedirect("/day06/index.jsp");


     

1.8  : response细节

1、getOutputStream和getWriter方法分别用于得到输出二进制数据、输出文本数据的ServletOuputStream、Printwriter对象。


2.getOutputStream和getWriter这两个方法互相排斥,调用了其中的任何一个方法后,就不能再调用另一方法,包括转发时。

   重定向可以,因为向服务器发送两次请求。

    如果需要同时写入字节或者字符时使用:字节流的方法 getOutputStream( )


3.Servlet程序向ServletOutputStream或PrintWriter对象中写入的数据将被Servlet引擎从response里面获取,Servlet引擎将这些数据当

   作响应消息的正文,然后再与响应状态行和各响应头组合后输出到客户端。


4.Serlvet的service方法结束后,Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果

   没有,Servlet引擎将调用close方法关闭该输出流对象。

(不是从response获取,而是自己new的流对象记得关闭)

      
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值