1 ServletRequest接口
HttpServletRequest就是ServletRequest的子接口。我们再调用Servlet的service(ServletRequest request, ServletResponse response)的时候第一个参数就是ServletRequest接口类型。
ServletRequest表示来自客户端的请求。当Servlet容器收到客户端要求访问特定的Servlet请求的时候,容器首先解析客户端请求上来的原始数据,然后把它们包装成一个ServletRequest的对象。当容器调用service方法的时候,该对象就会传递给service方法。
ServletRequest提供了一系列的处理客户端请求数据的方法:
-
getContentLength():返回请求正文的长度,如果请求正文的长度为空,返回-1
-
getContentType():获得请求政委的mine类型,如果请求正文为空,返回null
-
getInputStream():返回用于读取正文的输入流 getLocalAddr():返回服务器端的Ip地址
-
getLocalName():返回服务器端的主机名 getLocalPort():返回应用服务器的端口号
-
getParameter(String name):根据指定的名字,返回来自客户端请求中匹配的请求参数值,包括Get和Post的参数
-
getProtocol():返回客户端与服务器端通信所用的协议的名称以及版本号
-
getReader():返回用于读取字符串形式的请求正文的BufferedReader对象
-
getRemoteAddr():返回客户端的Ip地址 getRemoteHost():返回客户端的主机名
-
getRemotePort():返回客户端的端口号
ServletRequest还定义了一组在请求范围内共享数据的方法。
- setAttribute(String name, Object
object):在请求范围内保存一个属性,参数name表示属性名,参数Object表示属性值。 - getAttribute(String name):根据name参数给定的属性名,返回请求范围内匹配的属性值
2 HttpServletRequest接口
HttpServletRequest接口是ServletRequest接口的子接口。在HttpServlet类重载service方法以及提供的doXXX方法里面有一个参数就是HttpServletRequest。
HttpServletRequest接口提供了用于读取Http请求中相关信息的方法:
- getContextPath():返回客户端所请求访问的Web应用的URL入口,比如,我们访问的是
- http://localhost:8080/001helloword/login,name该方法返回/001helloword。
- getCookies():返回Http请求中所有的Cookie
- getHeader(String name):返回Http请求头部特定项
- getHeaderNames():返回一个Enumeration对象,他包含了Http请求头中所有的项目名
- getMethpd():返回Http请求方式
- getRequestURI:返回Http请求头中的第一行的URI
- getQueryString():返回查询字符串,就是?后面的东西
3 ServletRequest和HttpServletRequest的作用:
我们使用Servlet Api 来创建Servlet的时候,无须费力的解析原始Http请求。原始内容的解析,直接交给HttpServletRequest对象就好了。我们程序员只需要调用各种getXXX方法来获取对应的数据就行了。
4 Request相关实例
package com.vgxit.helloworld.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
/**
* HttpServletRequest的具体案例
*/
public class RequestInfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1,设置响应正文类型
response.setContentType("text/html;charset=utf-8");
//2,获取request里面的各种信息,并展示在页面上
try (PrintWriter pw