JavaWeb ( HttpServletRequest,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的流对象记得关闭)

      
1.1   HttpServletRequest

HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,

开发人员通过这个对象的方法,可以获得客户这些信息。


request获取数据的常用方法:

getRequestURL方法返回客户端发出请求时的完整URL。

getRequestURI方法返回请求行中的资源名部分。

getQueryString 方法返回请求行中的参数部分。

getPathInfo方法返回请求URL中的额外路径信息。额外路径信息是请求URL中的位于Servlet的路径之后和查询参数之前的内容,它以“/”开头。

getRemoteAddr方法返回发出请求的客户机的IP地址

getRemoteHost方法返回发出请求的客户机的完整主机名

getRemotePort方法返回客户机所使用的网络端口号

getLocalAddr方法返回WEB服务器的IP地址。

getLocalName方法返回WEB服务器的主机名


获得客户机请求头

getHeader方法         getHeaders方法              getHeaderNames方法


获得客户机请求参数(客户端提交的数据)

getParameter方法                getParameterValues(String name)方法              getParameterNames方法                  getParameterMap方法


1.2   请求头以及各种表单输入项数据的获取

//数据提交表单

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>带数据给requestDemo3</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">    
  </head>  
  <body>
    <br>
    <!-- Url后跟中文数据要编码后提交--> 
    <form action="/day06/RequestMethod" method="post">
    	 用户名1
:<input type="text" name="username"/><br/>
       	 密码:
<input type="password" name="password"/><br/>
       	 性别:
       	 <input type="radio" name="gender" value="male" />男
       	 <input type="radio" name="gender" value="female" />女 <br/>
       	 
       	 所在地:<select name="city">
       	 	<option value="beijing">北京</option>
       	 	<option value="shanghai">上海</option>
       	 	<option value="cs">广州</option>
       	 </select><br/>
       	 爱好:
       	 <input type="checkbox" name ="likes" value="reading" />看書
       	 <input type="checkbox" name ="likes" value="swimming" />游泳
       	 <input type="checkbox" name ="likes" value="basketball" /> 篮球
       	 <input type="checkbox" name ="likes" value="football" />足球
       	 <br/>
       	 备注:<textarea rows="5" cols="60" name="description"  ></textarea>
       	 <br/>
       	 大头照<input type="file" name="image" /><br/>
       	 <input type="hidden" name="id" value="123456"/>
       	 
    	 <input type="submit" value="提交"/>
    </form>
  </body>
</html>
	

客户对象,通过beanutils的getParameterMap( )获取

package cn.xushuai.exercise;

public class User {
	private String username[];
	private String password;
	
	public void setUsername(String username[]) {
		this.username = username;
	}
	
	public String[] getUsername(){
		return username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
}


//获取各种数据的源代码

package cn.xushuai.exercise;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

//获取数据时一定要先检验是否为空
public class RequestMethod extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		headerNames(request);	
		parameterNames(request);		
		parameterValues(request);	
		//parameterMap(request);
			
	}
//通過Beanutils以对象的形式获取
	private void parameterMap(HttpServletRequest request) {
		System.out.println("-----getParameterMap()-------");
		
                Map<String,String[]> map = request.getParameterMap();
		User user = new User();
		
		try{
			BeanUtils.populate(user,map);
		//只能拷贝8种基本类型,否则要自己创建一个转换器
			//BeanUtils.copyProperties(user,formbean);
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println(user);
	}

//获取指定名称的所有数据
	private void parameterValues(HttpServletRequest request) {
		System.out.println("-------getParameterValues()-------");
		
		String values[] = request.getParameterValues("likes");

		//获取请求头相关数据(一定要先检验在使用)
		for(int i=0;values!=null&& i<values.length;i++){
			System.out.println("likes = "+values[i]);
		}
	}
//获取参数名及值,如果有相同的参数名,只能获取到第一个值
	private void parameterNames(HttpServletRequest request) {
		System.out.println("-------getParameterNames()-------");
		
                Enumeration e = request.getParameterNames();
		while(e.hasMoreElements()){
			String name =(String)e.nextElement();
			String value = request.getParameter(name);
			System.out.println(name+": "+value);
		}
	}
//获取请求头的名称及值
	private void headerNames(HttpServletRequest request) {
		String headValue=request.getHeader("Accept-Encoding");
		
		System.out.println("--------- getHeaderNames()---------");	
		
                Enumeration e = request.getHeaderNames();
		while(e.hasMoreElements()){
			String name=(String) e.nextElement();
			String value=request.getHeader(name);
			System.out.println("name="+name+",value="+value);
		}
	}	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}


1.3请求参数的中文乱码问题

浏览器以什么编码向服务器提交数据,在在浏览器中的:查看/编码下可看到,是你在做网页时指定的。

提交请求的方式

超链接,表单,直接在服务栏中请求

注意:超链接和表单默认的提交方式是Get


乱码原因:

在提交数据的时候,如果是中文(GBK或者UTF-8),在提交给服务端,在request处理的时候会进行ISO8859-1编码,而ISO8859-1编码不支持GBK,所以会解析成一些乱码


POST方式提交解决方法

request.setCharacterEncoding("GB2312");//放在request.getParameter()前面才有效

但是这种方式只对POST提交有用


GET方式提交解决方法(通用,也可以用于POST方式)

先进行ISO8859-1编码,以便服务器端可以识别,然后再使用ISO8859-1编码的字节进行GB2312解码,显示中文

String user = request.getParameter("user");

user = new String(user.getBytes("ISO8859-1"),"GB2312");//先进行ISO8859-1编码,这样服务器端可以识别,然后再使用GBK编码显示中文


可同时解决POST和GET(不推荐)

修改tomcat的配置文件:http://localhost:8080/docs/config/http.html

URIEncoding 指定服务端的编码

useBodyEncodingForURI:设为true,则POST的提交方式:request.setCharacterEncoding("GB2312");对GET方式也有用

 <Connector port="8080" protocol="HTTP/1.1"
              connectionTimeout="20000"
              redirectPort="8443"
              URIEncoding="UTF-8" />
<Connector port="8080"protocol="HTTP/1.1"
              connectionTimeout="20000"
              redirectPort="8443"
              useBodyEncodingForURI="true" />


方式一:

//提交表单源代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

	<meta http-equiv="keywords" content="keyword1,keyword2">
	<meta http-equiv="description" content="this is my page">
	<meta http-equiv="content-type" content="text/html;charset=UTF-8">
</head>
<body>
	<form action="/day06/RequestConfusedCode" method="post">
	用户名:<input type="text" name="username" ><br/>
	密码:<input type="password" name="password"><br/>
	<input type="submit"  value="提交">
	</form>
	
	<a href="/day06/RequestConfusedCode?username=中国">链接</a>
</body>
</html>

//doGet和doPost解决表单提交源代码

package cn.xushuai.exercise;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

public class RequestConfusedCode extends HttpServlet {
	private static final long serialVersionUID = 1L;     
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//getTest(request,response);
		postTest(request);	
	}

	private void postTest(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		String username=request.getParameter("username");
		System.out.println(username);
	}

	private void getTest(HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException,
			IOException {
		request.setCharacterEncoding("UTF-8");
		String value = request.getParameter("username");
		
		//先进行ISO8859-1编码,这样服务器端可以识别,然后再使用GBK编码显示中文
		//byte[] codeValue = value.getBytes("ISO-8859-1");
		//String realVal = new String(codeValue,"UTF-8");
		String realVal = new String(value.getBytes("ISO8859-1"),"UTF-8");
		System.out.println(realVal);
		
		//上面代码相当于获取"中国"
		response.setCharacterEncoding("gb2312");
		response.setContentType("text/html;charset=gb2312");
		response.getWriter().print(realVal);
	}

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

}

1.4  request利用请求域传递对象

request对象同时也是一个域对象,开发人员通过request对象在实现转发时,把数据通过request对象带给其它web资源处理

setAttribute方法 
getAttribute方法  
removeAttribute方法
getAttributeNames方法
request作用域的作用范围

注意:所谓的request域是指在整个请求链上有效
  request在实现请求转发的时候,第一个request中的信息会复制一份传给第二个request,所以可以从另一个servlet中获取到上一个servlet的request中的数据,
  因为它们在同一个请求链。


理解错误:
认为Context代表整个应用,所以在Context中存入的Request中无法取到,本质上就不是一个容器,而且获取时使用的就不是同一个对象
1.4   request对象实现请求转发:求转发指一个web资源收到客户端请求后,通知服务器去调用另外一个web资源进行处理。

1、request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发,从而共享请求中的数据

2、如果在调用forward方法之前向servlet程序中写入的部分内容已经被真正的传送到了客户端(f已经lush了)forward将不能进行,会抛出异常。 

3、如果在调用forward之前向response缓冲区中写入了内容,只要写入到其中的内容还没有真的被输出到客户端,forward方法就可以正常执行,但原来写入到缓冲区中的数据将被清空,注意只是实体内容被清空,之前写入的响应头信息仍然存在。

(使用include可以解决3中之前的request缓冲区被清空的问题)


请求转发的应用场景:MVC(model view cotroller)设计模式


request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发。

request对象同时也是一个域对象,开发人员通过request对象在实现转发时,把数据通过request对象带给其它web资源处理。

setAttribute方法               getAttribute方法  

removeAttribute方法       getAttributeNames方法


Jsp代码 <%

   String mess=(String)request.getAttribute("message");

   out.write(mess);   

     %>


servlet代码

String message="aaaaaa";

request.setAttribute("data",message);

request.getRequestDispatcher("/mesage.jsp").forward(request,response);


1.5  请求转发的细节

1. forward方法用于将请求转发到RequestDispatcher对象封装的资源。


   请求转发的特点:

        1>客户端只发一次,而服务端有多个资源调用

        2>客户端浏览器地址栏没有变化


2.如果在调用forward方法之前,在Servlet程序中写入的部分内容已经被真正地传送到了客户端,forward方法将抛出

         java.lang.IllegalStateExceptio:Cannot forward after response has beencommitted. 


   解决方案:在跳转语句之后通过添加return语句来避免

1.6  请求重定向和请求转发的区别

1. 定义:

      请求重发:一个web资源收到客户端请求后,通知服务器去调用另外一个web资源进行处理

      请求重定向:一个web资源收到客户端请求后,通知浏览器去访问另外一个web资源

 

2. RequestDispatcher.forward方法只能将请求转发给同一个WEB应用中的组件;而HttpServletResponse.sendRedirect方法还

可以重定向到同一个站点上的其他应用程序中的资源,甚至是使用绝对URL重定向到其他站点的资源。

 

3. 如果传递给HttpServletResponse.sendRedirect 方法的相对URL以“/”开头,它是相对于整个WEB站点的根目录;如果创建

    RequestDispatcher对象时指定的相对URL以“/”开头,它是相对于当前WEB应用程序的根目录。


4. 调用HttpServletResponse.sendRedirect方法重定向的访问过程结束后,浏览器地址栏中显示的URL会发生改变,由初始的

   URL地址变成重定向的目标URL;调用RequestDispatcher.forward方法的请求转发过程结束后,浏览器地址栏保持初始的URL地址不变。

 

5. HttpServletResponse.sendRedirect方法对浏览器的请求直接作出响应,响应的结果就是告诉浏览器去重新发出对另外一个

    URL的访问请求;RequestDispatcher.forward方法在服务器端内部将请求转发给另外一个资源,浏览器只知道发出了请求

     并得到了响应结果,并不知道在服务器程序内部发生了转发行为。

 

6. RequestDispatcher.forward方法的调用者与被调用者之间共享相同的request对象和response对象,它们属于同一个访问请求

    和响应过程;而HttpServletResponse.sendRedirect方法调用者与被调用者使用各自的request对象和response对象,它们属于

     两个独立的访问请求和响应过程。


应用区别:

相同点:两者都可以进行页面跳转


不同点:

1、请求重定向造成两次请求和响应,请求转发只有一次,重定向会造成两倍的访问量,提高了服务器的压力,所以,通常情况下使用

请求转发处理页面跳转

2、请求重定向导致地址栏发生变化,请求转发地址栏不变,如果我们明确的想要改变地址栏,就使用重定向,如注册后跳转到主页,防盗链

时跳转到主页。

3、请求重定向后更新了刷新操作,刷新将是访问跳转后的页面(刷新就是把上次做的事情重做一次)。请求转发的书信没有更新,刷新

将是重新做一次跳转前的事情,这在某些情况下会造成问题:

如注册后跳转到主页的过程,如果是请求转发,一刷新,又注册了一次,

网购的时候,点击购买,如果用的是请求转发,一刷新,又多买了一件。


请求重定向的两种方式

方式一:利用response设置状态码为302,并设置响应头Location为要重定向到的地址,就可以实现请求重定向操作了。

response.setStatus(302);

response.setHeader("Location", "....");

方式二:response.setRedirec("....");实现请求重定向。


请求转发的两种方式

this.getServletContext().getRequestDispatcher("....").forward(request, response);

request.getRequestDispatcher("....");


1. 7RequestDispatcher

include方法:


1、RequestDispatcher.include方法用于将RequestDispatcher对象封装的资源内容作为当前响应内容的一部分包含进来,从而实现可编程

 的服务器端包含功能。

2、被包含的Servlet程序不能改变响应消息的状态码和响应头,如果它里面存在这样的语句,这些语句的执行结果将被忽略。

3、include在程序执行上效果类似forward,但是使用forward只有一个程序可以生成响应,include可以由多个程序一同生成响应 ----- 常用来页面布局

注意:

1、被包含的Servlet程序不能改变响应消息的状态码和响应头,如果它里面存在这样的语句,这些语句的执行结果将被忽略

2、在页面包含的时候,注意格式的良好,保证全局标签只出现一次


request.getRequestDispatcher("/public/head.jsp").include(request,response);

response.getWriter().write("hahaha");

request.getRequestDispatcher("/public/foot.jsp").include(request,response);

1.8   : 防盗链

在地址栏里输入请求路径,refere为null,所以可以根据refere是否为null来判断是否从本网站还是直接复制地址到地址栏去访问私有资源

这里的私有资源 news.html 放在WEB-INF路径下而不是WEBROOT下,这样是防止其它人直接可以访问到

假如资源所在路径为:http://localhost:8080/day05/RefererDemo

在地址栏里直接输入,referer为null,所以就让它跳转到自己的主页,看过新闻之后就可以进入私有资源


为防盗而跳转的页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>news.jsp</title>
</head>
<body>
		<br/>新闻首页<br/>
	<a href="/day06/ProtectedLine">中国解放军收复钓鱼岛</a>  
	
</body>
</html>

防盗链源代码
package cn.xushuai.exercise;

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 ProtectedLine extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String referer = request.getHeader("referer");
		
		if(referer==null || !referer.startsWith("http://localhost?ads")){
			response.sendRedirect("/day06/news.jsp");
			return ;
		}
		response.setContentType("text/html;charset=UTF-8");
		String data = "中国解放军收复钓鱼岛";
		response.getWriter().write(data);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}	

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值