Servlet—HttpServletRequest

HttpServletRequest

HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,开发人员通过这个对象的方法,可以获得客户这些信息。

1.  常用方法

1.1 获取基本信息

getRequestURL返回客户端发出请求时的完整URL。
getRequestURI返回请求行中的资源名部分。
getQueryString 返回请求行中的参数部分。
getRemoteAddr返回发出请求的客户机的IP地址
getRemoteHost返回发出请求的客户机的完整主机名
getRemotePort返回客户机所使用的网络端口号
getLocalAddr返回WEB服务器的IP地址。
getLocalName返回WEB服务器的主机名
getMethod:得到客户机请求方式

演示:


package com.oner.request;

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 RequestDemo extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		System.out.println("URI:" + request.getRequestURI());
		System.out.println("URL:" + request.getRequestURL());
		System.out.println("-------------");
		System.out.println("QueryString:" + request.getQueryString());
		System.out.println("-------------");
		System.out.println("RemoteAddr:" + request.getRemoteAddr());
		System.out.println("RemoteHost:" + request.getRemoteHost());
		System.out.println("RemotePort:" + request.getRemotePort());
		System.out.println("-------------");
		System.out.println("LocalAddr:" + request.getLocalAddr());
		System.out.println("LocalName:" + request.getLocalName());
		System.out.println("-------------");
		System.out.println("Method:" + request.getMethod());
	}

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

}

在浏览器地址中输入:http://localhost:8080/day06/RequestDemo?name=oner&age=18

查看控制台:



1.2 获取客户机请求头

getHead(name)方法
getHeaders(String name)方法
getHeaderNames方法

package com.oner.request;

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

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

//获取请求头和请求数据
public class RequestDemo2 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		test1(request);
	}

	// 获取请求头相关的方法
	private void test1(HttpServletRequest request) {
		String headValue = request.getHeader("Accept-Encoding");
		System.out.println(headValue);
		System.out.println("-----------");
		Enumeration<String> e = request.getHeaders("Accept-Encoding");
		while (e.hasMoreElements()) {
			String value = e.nextElement();
			System.out.println(value);
		}
		System.out.println("-----------");
		e = request.getHeaderNames();
		while (e.hasMoreElements()) {
			String name = e.nextElement();
			String value = request.getHeader(name);
			System.out.println(name + "=" + value);
		}
	}

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

}


在浏览器中输入http://localhost:8080/day06/RequestDemo2,回车,查看控制台:



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

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

getInputStream

package com.oner.request;

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

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

//获取请求头
//获取请求数据(一般来说都要先检查再使用)
public class RequestDemo2 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		// test1(request);
		System.out.println("----获取数据方式1----");
		String name;
		String value = request.getParameter("username");
		// 先检查
		if (value != null && !value.trim().equals("")) {
			System.out.println(value);
		}
		System.out.println("----获取数据方式2----");
		Enumeration<String> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			name = e.nextElement();
			value = request.getParameter(name);
			System.out.println(name + "=" + value);
		}
		System.out.println("----获取数据方式3----");
		String[] namevalues = request.getParameterValues("username");
		for (int i = 0; namevalues != null && i < namevalues.length; i++) {
			name = namevalues[i];
			System.out.println(name);
		}
		System.out.println("----获取数据方式4----");
		Map<String, String[]> map = request.getParameterMap();
		// 获取所有键值对对象的集合
		Set<Map.Entry<String, String[]>> set = map.entrySet();
		for (Map.Entry<String, String[]> me : set) {
			name = me.getKey();
			String values[] = me.getValue();
			for (int i = 0; values != null && i < values.length; i++) {
				value = values[i];
				System.out.println(name + "=" + value);
			}

		}

		// 通过流获取
		InputStream in = request.getInputStream(); // 这种方式只用在文件上传上
	}

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

}


在浏览器地址中输入:http://localhost:8080/day06/test.html,回车后在表单中填入数据后点击提交


查看控制台:


1.4  通过表单收集客户机数据

    有时候需要通过表单收集客户机数据,该怎么实现呢?

先来一个form.html表单:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form.html</title>
</head>
<body>
	<form action="/day06/RequestDemo3" method="post">
		用户名:<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="guangzhou">广州</option>
		</select><br/>
		爱好:
		<input type="checkbox" name="likes" value="sing"/>唱歌
		<input type="checkbox" name="likes" value="dance"/>跳舞
		<input type="checkbox" name="likes" value="basketball"/>篮球
		<input type="checkbox" name="likes" value="football"/>足球<br/>
		自我介绍:
		<textarea rows="6" cols="5" name="description"></textarea><br/>
		上传照片:
		<input type="file" name="image"/><br/>
		<input type="hidden" name="id" value="12345"><br/>
		
		<input type="submit" value="提交" />
	</form>
</body>
</html>


获取数据:

package com.oner.request;

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 RequestDemo3 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String username = request.getParameter("username");
		if (username != null && !username.trim().equals("")) {
			System.out.println("username=" + username);
		}
		String password = request.getParameter("password");
		System.out.println("password=" + password);

		String gender = request.getParameter("gender");
		if (gender != null) {
			System.out.println("gender=" + gender);
		}
		String city = request.getParameter("city");
		System.out.println("city=" + city);
		String[] likes = request.getParameterValues("likes");
		// 这里必须要设置likes!=null来检测是否为空,否则用户如果没有选择likes就提交就会抛出NullPointerException
		for (int i = 0; likes != null && i < likes.length; i++) {
			System.out.println("likes=" + likes[i]);
		}

		String description = request.getParameter("description");
		System.out.println("description=" + description);
		// request.getAttribute("image");
		String id = request.getParameter("id");
		System.out.println("id=" + id);

	}

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

}


在浏览器地址中输入http://localhost:8080/day06/form.html,回车:


填写数据后提交,然后就能在控制台上看到提交的数据了。

2. Request中文乱码问题

当用户提交数据时,默认使用的编码格式为浏览器当前页面所用的编码格式,一般为GBK或UTF-8,在servlet里使用request的getParameter(name)方法获取用户提交的数据时,默认是使用iso编码打开的,所用会造成乱码。为解决这个问题,设置request的编码格式,需要注意到是,POST和GET提交方式的设置方式是不同的。

form2.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Request中文乱码</title>
</head>
<body>
	<form action="/day06/RequestDemo4" method=post>
		用户名1:
		<input type="text" name="username"/>
		<input type="submit" value="提交"/>
	</form><br/>
	<form action="/day06/RequestDemo4" method=get>
		用户名2:
		<input type="text" name="username"/>
		<input type="submit" value="提交"/>
	</form><br/>
</body>
</html>


2.1 POST提交方式

servlet:

package com.oner.request;

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 RequestDemo4 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		request.setCharacterEncoding("UTF-8");// 只对post提交有效,对get无效
		String username = request.getParameter("username");
		System.out.println(username);

	}

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

}


浏览器地址输入:http://localhost:8080/day06/form2.html,回车,在“用户名1”的输入项中输入中文数据


点击提交,查看控制台:



2.2 GET提交方式

package com.oner.request;

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 RequestDemo4 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		// 如为get提交,username中的乱码想正常,只能采用如下方式手工处理
		String username = request.getParameter("username");
		username = new String(username.getBytes("iso8859-1"), "UTF-8");
		System.out.println(username);

	}

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

}


浏览器地址输入:http://localhost:8080/day06/form2.html,回车,在“用户名2”后面的输入项中输入中文:


点击提交,查看控制台:


如果使用超链接中也附带了提交数据,也会出现乱码问题:

form3.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>URL携带中文数据</title>
</head>
<body>
	<!-- 超链接中提交的数据如果包含中文,也只能手工处理 -->
	<a href="/day06/RequestDemo4?username=中国">点击</a>
</body>
</html>


servlet:

package com.oner.request;

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 RequestDemo4 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String username = request.getParameter("username");
		System.out.println(username);

	}

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

}


在浏览器地址中输入http://localhost:8080/day06/form3.html,回车:


点击“点击按钮”,查看控制台:



这也需要通过手工处理来解决:

package com.oner.request;

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 RequestDemo4 extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
		String username = request.getParameter("username");
		username = new String(username.getBytes("iso8859-1"), "UTF-8");
		System.out.println(username);

	}

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

}


再次在浏览器地址中输入:http://localhost:8080/day06/form3.html,回车后点击“点击”按钮,查看控制台:



这里思考下一个问题,假如在一个getDo方法中有如下逻辑,在客户端提交中文数据,最后在浏览器页面上会不会出现乱码问题呢?

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

		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");

		response.setCharacterEncoding("gb2312");
		response.setContentType("text/html;charset=gb2312");
		response.getWriter().write(username);

	}


答案是需要看客户端的数据提交方式,如果为post,不会出现乱码,如果为get,就会。为什么呢?

如果是post提交方式,doGet方法里的前两句话保证了servlet可以正确的从客户端拿到中文数据(客户端以UTF-8格式写数据,response以UTF-8读取数据),后面的三句话保证了客户端能正确的从servlet拿到中文数据(response以GB2312格式写入数据,客户端以GB2312格式读取数据),所以最后不会出现乱码。

如果是get提交方式,doGet方法里的前两句话并不能保证servlet可以正确的从客户端拿到中文数据,所以会出现乱码。

3. 使用request实现请求转发

    前面学习了使用ServletContext实现请求转发,那么为什么还需要学习request来实现请求转发呢?先回顾一下使用ServletContext实现请求转发的场景,假设ServletA要向ServletB实现请求转发,要转发的数据data=“hello world!”。在ServletA中它会先调用getServletContext().setAttribute("data", data),然后调用getServletContext().getRequestDispatcher("/ServletB").forward(request, response)告诉ServletB来实现转发。

在ServletB中它会先调用getServletContext().getAttribute("data")得到数据data。代码实现如下:

ServletA中的getDo()方法:

    protected void doGet(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
  
        String data = "hello world!";  
  
        ServletContext context = this.getServletContext();  
        context.setAttribute("data", data);  
  
        RequestDispatcher rd = context.getRequestDispatcher("/ServletB");  
        rd.forward(request, response);  
    } 


ServletB中的getDo()方法:

    protected void doGet(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
        String data = (String) this.getServletContext().getAttribute("data");  
    } 


上面用ServletContext实现数据共享以及请求转发逻辑上并没有什么问题,但是假设在ServletA中使用ServletContext对象调用setAttribute()方法将data设置为“hello world!”后,紧接着有一个ServletC也使用ServletContext对象调用setAttribute()方法将data设置为“hello  web!”,由于ServletContext域的作用范围是整个web应用,且每个web应用共享一个ServletContext对象,所以这时候data的数据已经被覆盖成了“hello web!”,之后ServletA再调用getRequestDispatcher("/ServletB")来告诉ServletB来实现请求转发,这时ServletB中使用getAttribute()方法得到的data就变成了“hello web!”。


可以使用request来实现请求转发,request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发。同时,request对象也是一个域对象,开发人员通过request对象在实现转发时,把数据通过request对象带给其它web资源处理。


演示:

Servlet:

package com.oner.request;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//请求转发,以及使用request域对象把数据带给转发资源
/*
 在mvc(model view cotroller)设计模式下,都是servlet处理用户请求,并产生用户想看的数据,然后转交给jsp显示,转交给jsp显示时,
 会把数据存在request域里面带给jsp
 */
public class RequestDemo5 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String data = "hello web!";
		// 使用ServletContext实现请求转发
		// this.getServletContext().setAttribute("data", data);

		// 使用request实现请求转发
		request.setAttribute("data", data);
		request.getRequestDispatcher("/message.jsp").forward(request, response);

	}

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

}



message.jsp:

<%@ 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>message.jsp</title>
</head>
<body>

	<!-- 
	<%//得到refresh刷新头以及“登陆成功...”信息
			String message = (String) application.getAttribute("message");
			//将数据写出
			out.write(message);
	%>
	 -->
	
	<!-- 一种获取方式 -->
	${data }<br/>
	<!-- 另一种获取方式 -->
	<%
		String data = (String) request.getAttribute("data");
		out.write(data);
	%>
</body>
</html>


在浏览器地址中输入:http://localhost:8080/day06/RequestDemo5,回车:



4. 利用referer制作防盗链

现在网站的盈利模式大多数都是广告,假如一个公司提供小说《雪中悍刀行》的资源(该资源在web应用中的ServletA中),而该公司网站的广告主要放在index页面,且index页面中包含进入ServletA的超链接,如果用户直接访问ServletA中的资源,或者经过其他别竞争的公司网站访问ServletA中的资源,而没有经过index页面(如果这样,该公司的广告点击率就会很低,盈利也会很低),为了避免这种情况的发生,可以检测用户是不是直接访问的ServletA或者是不是通过别的公司的网站进入,怎么检测呢?通过referer这个请求头可以实现,然后通过请求重定向来实现转到index页面。

ServletDemo9(代替上面中的ServletA):

package com.oner.request;

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 RequestDemo9 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String referer = request.getHeader("referer");
		// 当referer==null或者referer不以指定路径开头时
		if (referer == null || !referer.startsWith("http://localhost")) {
			// 使用重定向将页面转到index.jsp
			response.sendRedirect("/day06/index.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);
	}

}


index.jsp:

<%@ 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>index.jsp</title>
</head>
<body>

	<!-- 
		<p><font color="orange">这是网站的主页!</font></p>
		<a href="/day06/ResponseDemo6">连接</a>
	 -->
	
	<!-- index这个页面可以放置一些广告,把真正需要的连接放在最下面 -->
	广告1.....<br/>
	广告2.....<br/>
	广告3.....<br/>
	广告4.....<br/><br/>
	<a href="/day06/RequestDemo9">点击进入雪中悍刀行目录</a>

</body>
</html>


在浏览器地址中直接输入http://localhost:8080/day06/RequestDemo9,回车,发现地址栏编程了index.jsp:


点击下面的超链接,就进入了要访问的资源了.


5.  实现页面包含

RequestDispatcher.include方法用于将RequestDispatcher对象封装的资源内容作为当前响应内容的一部分包含进来,从而实现可编程的服务器端包含功能。被包含的Servlet程序不能改变响应消息的状态码和响应头,如果它里面存在这样的语句,这些语句的执行结果将被忽略。

假设想要将WEB-INF/public/head.jsp和foot.jsp内容作为相应内容包含起来。

head.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>

head


foot.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>

foot


演示:

package com.oner.request;

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 RequestDemo8 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

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

		response.getWriter().write("<br/>hello web!<br/>");

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

	}

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

}


在浏览器地址中输入:http://localhost:8080/day06/RequestDemo8,回车:


6. forward方法的一些细节

细节1:

forward方法用于将请求转发到RequestDispatcher对象封装的资源。如果在调用forward方法之前,在Servlet程序中写入的部分内容已经被真正地传送到了客户端,forward方法将抛出IllegalStateException异常。

演示一下:

package com.oner.request;

import java.io.IOException;
import java.io.PrintWriter;

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

//forward方法的细节
public class RequestDemo6 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String data = "hello web!";

		// 判断某个条件,如果成立,就跳转到index.jsp页面
		if (true) {
			request.getRequestDispatcher("/index.jsp").forward(request,
					response);
		}

		/*
		 * 中间是一些其他代码
		 */

		// 由于加上了一些中间的其他代码,可能忘记上面已经使用request调用过forward方法,所以又再一次使用了forward方法
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		
	}

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

}

在浏览器地址中输入:http://localhost:8080/day06/RequestDemo6,回车:



发现在RequestDemo6的32行抛出了IllegalStateException异常,这时由于在之前已经使用forward方法跳转到了index.jsp页面,这儿又再次使用,所以抛出了异常。

解决办法是在每次跳转后都加上return;语句。

package com.oner.request;

import java.io.IOException;
import java.io.PrintWriter;

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

//forward方法的细节
public class RequestDemo6 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String data = "hello web!";

		// 判断某个条件,如果成立,就跳转到index.jsp页面
		if (true) {
			request.getRequestDispatcher("/index.jsp").forward(request,
					response);
			return;// 加上return语句
		}

		/*
		 * 中间是一些其他代码
		 */

		// 由于加上了一些中间的其他代码,可能忘记上面已经使用request调用过forward方法,所以又再一次使用了forward方法
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		return;// 加上return语句

	}

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

}


再次在浏览器地址中输入:http://localhost:8080/day06/RequestDemo6,回车:



细节2:

如果在调用forward方法之前向Servlet引擎的缓冲区(response)中写入了内容,只要写入到缓冲区中的内容还没有被真正输出到客户端,forward方法就可以被正常执行,原来写入到输出缓冲区中的内容将被清空,但是,已写入到HttpServletResponse对象中的响应头字段信息保持有效。

演示:

package com.oner.request;

import java.io.IOException;

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

//forward方法的细节:forward会清空response中的数据
public class RequestDemo7 extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		response.setContentType("text/html;charset=UTF-8");

		String data = "hello web!";
		response.getWriter().write(data);// 只是将数据写入了response中,并没有真正写到浏览器

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

	}

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

}


在浏览器地址中输入:http://localhost:8080/day06/RequestDemo7,回车:



浏览器显示的只是index.jsp中的内容,并没有显示出“hello web!”,说明forward方法清空了之前response中的内容。

7. web工程中各类地址的写法

package com.oner;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
只要是写地址,建议大家最好以"/"开头,/到底代表什么呢?
	1.看这个地址是给服务器用的,还是给浏览器用的。
	2.如果给浏览器用的,/代表网站  (webapps)
	3.如果给服务器用的,/代表当前web应用
 
*/
public class ServletDemo extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		// 1.针对服务器
		request.getRequestDispatcher("/form.html").forward(request, response);

		// 2. 针对浏览器
		response.sendRedirect("/day06/form1.html");

		// 3.针对服务器
		this.getServletContext().getRealPath("/form.html");

		// 4.针对服务器
		this.getServletContext().getResourceAsStream("/public/foot.jsp");

		// 5.针对浏览器
		/*
		 * <form action="/day06/RequestDemo8"> </form>
		 */

		// 6.
		// <a href="/day06/....">点点</a>
	}

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

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值