首页 > 其他分享 >HttpServletRequest客户请求对象详解

HttpServletRequest客户请求对象详解

时间:2023-10-24 13:05:45浏览次数:26  
标签:HttpServletRequest 请求 request System 详解 println String

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

方法

1.获取客户机信息

方法声明

功能描述

String getMethod()

该方法用于获取HTTP请求消息中的请求方式(如GET、POST等)

String getRequestURI()

该方法用于获取请求行中资源名称部分,即位于URL的主机和端口之后、参数部分之前的部分

String getQueryString()

该方法用于获取请求行中的参数部分,也就是资源路径后面问号(?)以后的所有内容

String getProtocol()

该方法用于获取请求行中的协议名和版本,例如,HTTP/1.0或HTTP/1.1

String getContextPath()

该方法用于获取请求URL中属于WEB应用程序的路径,这个路径以“/”开头,表示相对于整个WEB站点的根目录,路径结尾不含“/”。

如果请求URL属于WEB站点的根目录,那么返回结果为空字符串("")

String getServletPath()

该方法用于获取Servlet所映射的路径(url-pattern)

String getRemoteAddr()

该方法用于获取请求客户端的IP地址,其格式类似于“192.168.0.3”

String getRemoteHost()

该方法用于获取请求客户端的完整主机名,其格式类似于“www.sw.com”。

需要注意的是,如果无法解析出客户机的完整主机名,该方法将会返回客户端的IP地址

String getRemotePort()

该方法用于获取请求客户端网络连接的端口号

String getLocalAddr()

该方法用于获取Web服务器上接收当前请求网络连接的IP地址

String getLocalName()

该方法用于获取Web服务器上接收当前网络连接IP所对应的主机名

int getLocalPort()

该方法用于获取Web服务器上接收当前网络连接的端口号

String getServerName()

该方法用于获取当前请求所指向的主机名,即HTTP请求消息中Host头字段所对应的主机名部分

int getServerPort()

该方法用于获取当前请求所连接的服务器端口号,即如果HTTP请求消息中Host头字段所对应的端口号部分

String getScheme()

该方法用于获取请求的协议名,例如http、https或ftp

StringBuffer getRequestURL()

该方法用于获取客户端发出请求时的完整URL,包括协议、服务器名、端口号、资源路径等信息,但不包括后面的查询参数部分。

注意,getRequestURL()方法返回的结果是StringBuffer类型,而不是String类型,这样更便于对结果进行修改

2. 获得客户机请求头

方法声明

功能描述

String getHeader(String name)

该方法用于获取一个指定头字段的值,如果请求消息中没有包含指定的头字段,getHeader()方法返回null;

如果请求消息中包含有多个指定名称的头字段,getHeader()方法返回其中第一个头字段的值

Enumeration getHeaders(String name)

该方法返回一个Enumeration集合对象,该集合对象由请求消息中出现的某个指定名称的所有头字段值组成。

在多数情况下,一个头字段名在请求消息中只出现一次,但有时候可能会出现多次

Enumeration getHeaderNames()

该方法用于获取一个包含所有请求头字段的Enumeration对象

int getIntHeader(String name)

该方法用于获取指定名称的头字段,并且将其值转为int类型。需要注意的是,如果指定名称的头字段不存在,返回值为-1;

如果获取到的头字段的值不能转为int类型,将发生NumberFormatException异常

Long getDateHeader(String name)

该方法用于获取指定头字段的值,并将其按GMT时间格式转换成一个代表日期/时间的长整数,

这个长整数是自1970年1月1日0点0分0秒算起的以毫秒为单位的时间值

3. 获取请求参数

       方法声明

功能描述

String getParameter(String name)

该方法用于获取某个指定名称的参数值,如果请求消息中没有包含指定名称的参数,getParameter()方法返回null;

如果指定名称的参数存在但没有设置值,则返回一个空串;

如果请求消息中包含有多个该指定名称的参数,getParameter()方法返回第一个出现的参数值

String[] getParameterValues(String name)

HTTP请求消息中可以有多个相同名称的参数(通常由一个包含有多个同名的字段元素的FORM表单生成),

如果要获得HTTP请求消息中的同一个参数名所对应的所有参数值,那么就应该使用getParameterValues()方法,

该方法用于返回一个String类型的数组

Enumeration getParameterNames()

getParameterNames()方法用于返回一个包含请求消息中所有参数名的Enumeration对象,

在此基础上,可以对请求消息中的所有参数进行遍历处理

Map getParameterMap()

getParameterMap()方法用于将请求消息中的所有参数名和值装入进一个Map对象中返回

public class ServletRequestLearn extends HttpServlet {  
    @Override  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  
        //getAttribute(request);     ......
        //setCharacterEncoding(request);  
    }  
  
    /* 
     * setAttribute(String name,Object o):在请求中存储一个属性值 
     *  参数:name指定的参数值,o对应的name的value值 
     */  
    public static void setAttribute(HttpServletRequest request) {  
        String getAttribute = (String) request.getAttribute("myj");  
        System.err.println("getAttribute = " + getAttribute);  
        request.setAttribute("myj", "maomao");  
        String getSetAttribute = (String) request.getAttribute("myj");  
        System.err.println("getSetAttribute = " + getSetAttribute);  
    }  
  
    /* 
     * getParameterValues():获取一个参数的值,返回类型为Object类型的数组。 
     */  
    public static void getParameterValues(HttpServletRequest request) {  
        String params[] = request.getParameterValues("name");  
        for (int i = 0; i < params.length; i++) {  
            System.err.println(params[i]);  
        }  
    }  
  
    /* 
     * getParameterNames():返回一个Enumeration,包含请求中所有参数。 
     */  
    public static void getParameterNames(HttpServletRequest request) {  
        Enumeration enumParams = request.getParameterNames();  
        while (enumParams.hasMoreElements()) {  
            String obj = (String) enumParams.nextElement();  
            String getParams = request.getParameter(obj);  
            System.err.println(obj + " : " + getParams);  
        }  
    }  
  
    /* 
     * getParameterMap():返回请求中所有参数的形成的Map。 
     */  
    public static void getParameterMap(HttpServletRequest request) {  
        Map<String, String[]> map = request.getParameterMap();  
        Set<String> set = map.keySet();  
        Iterator<String> iterator = set.iterator();  
        while (iterator.hasNext()) {  
            String str = iterator.next();  
            String strArray[] = map.get(str);  
            for (int i = 0; i < strArray.length; i++) {  
                System.err.println(str + " : " + strArray[i]);  
            }  
        }  
    }  
  
    /* 
     * getAttribute(String name):返回指定名称的属性值 
     *  参数:name指定的参数值 
     */  
    public static void getAttribute(HttpServletRequest request) {  
        Object getAttribute = request.getAttribute("name");  
        System.err.println("getAttribute = " + getAttribute);  
    }  
  
    /* 
     * getParameter(String name):返回指定参数值,如果参数不存在则返回null。 
     *  参数:name指定的参数值 
     */  
    public static void getParameter(HttpServletRequest request) {  
        String getParameter = request.getParameter("name");  
        System.err.println("getParameter = " + getParameter);  
    }  
  
    /* 
     * getCharacterEncoding():返回请求体中使用的字符编码。 
     */  
    public static void getCharacterEncoding(HttpServletRequest request) {  
        String getCharacterEncoding = request.getCharacterEncoding();  
        System.err.println("getCharacterEncoding = " + getCharacterEncoding);  
    }  
  
    /* 
     * getContentLength(): 返回请求体和可用输入流的字节长度,返回-1标识长度未知。 
     */  
    public static void getContentLength(HttpServletRequest request) {  
        int getContentLength = request.getContentLength();  
        System.err.println("getContentLength = " + getContentLength);  
    }  
  
    /* 
     * getContentType():返回请求数据体的MIME类型,如果类型未知,返回空值 
     */  
    public static void getContentType(HttpServletRequest request) {  
        String getContentType = request.getContentType();  
        System.err.println("getContentType = " + getContentType);  
    }  
  
    /* 
     * getLocalAddr():返回发送请求的IP地址。(也就是客户端电脑的IP地址) 
     */  
    public static void getLocalAddr(HttpServletRequest request) {  
        String getLocalAddr = request.getLocalAddr();  
        System.err.println("getLocalAddr = " + getLocalAddr);  
        //127.0.0.1  
    }  
  
    /* 
     * getLocales():返回一个保存Locale对象的Enumeration对象,这些Locale对象都是客户端可接受的,并且Locale依据客户端的优先次序存储Enumeration。 
     */  
    public static void getLocales(HttpServletRequest request) {  
        Enumeration<Locale> getLocale = request.getLocales();  
        while (getLocale.hasMoreElements()) {  
            Locale local = getLocale.nextElement();  
            System.err.println("local = " + local.getCountry());  
            //zh_CN  
        }  
  
    }  
    /* 
     * getLocalName():返回发送请求的主机名称。 
     */  
  
    public static void getLocalName(HttpServletRequest request) {  
        String getLocalName = request.getLocalName();  
        System.err.println("getLocalName = " + getLocalName);  
        //如localhost  
    }  
      
    /* 
     * getLocale():返回客户端的Local对象,包含基于接受语言的头。(说明:java.util.Locale 对象表示了特定的地理、政治和文化地区。) 
     */  
    public static void getLocale(HttpServletRequest request) {  
        Locale getLocale = request.getLocale();  
        System.err.println("getLocale = " + getLocale);  
        //zh_CN  
    }  
      
    /* 
     * getLocalPort():返回发送请求的主机IP端口号。 
     */  
    public static void getLocalPort(HttpServletRequest request) {  
        int getLocalPort = request.getLocalPort();  
        System.err.println("getLocalPort = " + getLocalPort);  
        //如:8088  
    }  
      
    /* 
     * getProtocol(): 返回请求使用的协议名称和版本。 
     */  
    public static void getProtocol(HttpServletRequest request) {  
        String getProtocol = request.getProtocol();  
        System.err.println("getProtocol = " + getProtocol);  
        //如:HTTP/1.1  
    }  
      
    /* 
     * getRemoteAddr():获取发送请求的客户端或者最后代理主机的IP地址。 
     */  
    public static void getRemoteAddr(HttpServletRequest request) {  
        String getRemoteAddr = request.getRemoteAddr();  
        System.err.println("getRemoteAddr = " + getRemoteAddr);  
        //如127.0.0.1  
    }  
      
    /* 
     * getRemoteHost():获取发送请求的客户端或者最后代理主机的名称。 
     */  
    public static void getRemoteHost(HttpServletRequest request) {  
        String getRemoteHost = request.getRemoteHost();  
        System.err.println("getRemoteHost = " + getRemoteHost);  
        //如:127.0.0.1  
    }  
  
    /* 
     * getRemotePort():获取发送请求的客户端或者最后代理主机上的端口。 
     */  
    public static void getRemotePort(HttpServletRequest request) {  
        int getRemotePort = request.getRemotePort();  
        System.err.println("getRemotePort = " + getRemotePort);  
        //如3285,是会变得端口  
    }  
  
    /* 
     * getScheme():返回产生请求的模式名称,例如,http, https, ftp. 
     */  
    public static void getScheme(HttpServletRequest request) {  
        String getScheme = request.getScheme();  
        System.err.println("getScheme = " + getScheme);  
    }  
  
    /* 
     * getServerName():返回发送请求的主机名称。 
     */  
    public static void getServerName(HttpServletRequest request) {  
        String getServerName = request.getServerName();  
        System.err.println("getServerName = " + getServerName);  
        //如localhost  
    }  
  
    /* 
     * getServerPort():返回发送请求的主机端口。 
     */  
    public static void getServerPort(HttpServletRequest request) {  
        int getServerPort = request.getServerPort();  
        System.err.println("getServerPort = " + getServerPort);  
        //如8088  
    }  
  
    /* 
     * isSecure():返回是否使用安全通道。例如https。 
     */  
    public static void isSecure(HttpServletRequest request) {  
        boolean isSecure = request.isSecure();  
        System.err.println("isSecure = " + isSecure);  
        //如false  
    }  
  
    /* 
     * removeAttribute(String name):从请求中移除一个属性。 
     */  
    public static void removeAttribute(HttpServletRequest request) {  
        System.err.println("移除前name的值 = " + request.getAttribute("name"));  
        request.removeAttribute("name");  
        System.err.println("移除后name的值 = " + request.getAttribute("name"));  
    }  
  
    /* 
     * setCharacterEncoding(String name):重新设置请求体的字符编码。 
     *  参数:name指定的参数值 
     */  
    public static void setCharacterEncoding(HttpServletRequest request) throws UnsupportedEncodingException {  
        request.setCharacterEncoding("GBK");  
    }  
  
    /** 
     * ************************不是很懂得************************************************ 
     */  
    /* 
     * getAttributeNames():返回一个Enumeration包含请求可用到的所有属性名称。 
     */  
    /* 
     * getReader():获取请求体的BufferedReader对象表示。 
     */  
    public static void getReader(HttpServletRequest request) throws IOException {  
        BufferedReader params = request.getReader();  
        System.err.println(params);  
    }  
  
    /* 
     * getInputStream():输入流用来从请求体读取二进制数据。 
     */  
    public static void getInputStream(HttpServletRequest request) throws IOException {  
        ServletInputStream getInputStream = request.getInputStream();  
        System.err.println("getInputStream = " + getInputStream);  
    }  
  
    public static void getAttributeNames(HttpServletRequest request) {  
        Enumeration enumParames = request.getAttributeNames();  
        System.err.println("enumParames = " + enumParames);  
        while (enumParames.hasMoreElements()) {  
            //String getAttributeNames = (String) enumParames.nextElement();  
            //System.err.println("getAttributeNames = " + getAttributeNames);  
            Object obj = enumParames.nextElement();  
            System.err.println("obj = " + obj);  
        }  
    }  
}

例子

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
    System.out.println("getRequestURL: " + request.getRequestURL());
    System.out.println("getRequestURI: " + request.getRequestURI());
    System.out.println("getQueryString: " + request.getQueryString());
    System.out.println("getRemoteAddr: " + request.getRemoteAddr());
    System.out.println("getRemoteHost: " + request.getRemoteHost());
    System.out.println("getRemotePort: " + request.getRemotePort());
    System.out.println("getRemoteUser: " + request.getRemoteUser());
    System.out.println("getLocalAddr: " + request.getLocalAddr());
    System.out.println("getLocalName: " + request.getLocalName());
    System.out.println("getLocalPort: " + request.getLocalPort());
    System.out.println("getMethod: " + request.getMethod());
    System.out.println("-------request.getParamterMap()-------");
    //得到请求的参数Map,注意map的value是String数组类型  
    Map map = request.getParameterMap();
    Set < String > keySet = map.keySet();
    for (String key: keySet) {
        String[] values = (String[]) map.get(key);
        for (String value: values) {
            System.out.println(key + "=" + value);
        }
    }
    System.out.println("--------request.getHeader()--------");
    //得到请求头的name集合  
    Enumeration < String > em = request.getHeaderNames();
    while (em.hasMoreElements()) {
        String name = (String) em.nextElement();
        String value = request.getHeader(name);
        System.out.println(name + "=" + value);
    }
}

浏览器上地址栏输入:http://localhost:8080/RequestAndResponse/requestmethod?name=sunjob&password=123456&password=haha ,执行结果:


getRequestURL: http://localhost:8080/RequestAndResponse/requestmethod  
getRequestURI: /RequestAndResponse/requestmethod  
getQueryString: name=sunjob&password=123456&password=haha  
getRemoteAddr: 127.0.0.1  
getRemoteHost: 127.0.0.1  
getRemotePort: 2374  
getRemoteUser: null  
getLocalAddr: 127.0.0.1  
getLocalName: localhost  
getLocalPort: 8080  
getMethod: GET  
-------request.getParamterMap()-------  
name=sunjob  
password=123456  
password=haha  
--------request.getHeader()--------  
host=localhost:8080  
user-agent=Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20100101 Firefox/17.0  
accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
accept-language=zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3  
accept-encoding=gzip, deflate  
connection=keep-alive  
cache-control=max-age=0

总结

ServletRequest是通用request,提供一个request应该具有的最基本的方法,HttpServletRequest是ServletRequest的孩子,针对http协议进行了进一步的增强。


HttpServletRequest客户请求对象详解_System

标签:HttpServletRequest,请求,request,System,详解,println,String
From: https://blog.51cto.com/u_16248220/8002375

相关文章

  • Servlet Cookie对象详解
    Cookie是服务器发送给浏览器的体积很小的纯文本信息,用户以后访问同一个Web服务器时浏览器会把它们原样发送给服务器。cookie一般用于在线交易过程中标识用户身份、安全要求不高的场合避免用户重复输入名字和密码、门户网站的主页定制、有针对性地投放广告等等。 Servlet中可以同时......
  • Java中Servlet Filter配置(web.xml详解)
    Java中ServletFilter在web.xml中配置时有2个用于过滤器的元素,分别是filter和filter-mapping。filter元素向系统注册一个过滤对象,filter-mapping元素指定该过滤对象所应用的URL。Filter配置过滤器元素filter元素filter元素位于部署描述符文件(web.xml)的前部,所有filter-mapping、serv......
  • Chromium 消息循环和线程池详解
    Chromium中的多线程机制由base库提供,要理解Chromium中的多线程机制,首先要理解的概念就是 base::MessageLoop 和 base::TaskScheduler ,它们两个是Chromium多线程的基础1. MessageLoop详解base::MessageLoop 代表消息循环,它不会主动创建新的线程,默认情况下它使用当前......
  • Spring MVC入口Servlet详解(HttpServletBean,FrameworkServlet,DispatcherServlet )
    SpringMVC中DispatcherServlet前端控制器是web服务器的入口,那么它是怎么样进行初始化的,是怎么样进行工作?继承关系1.HttpServletBean主要做一些初始化的工作,将web.xml中配置的参数设置到Servlet中。比如servlet标签的子标签init-param标签中配置的参数。2.FrameworkServlet将Serv......
  • DispatcherServlet初始化顺序详解
    1. Web容器启动时将调用HttpServletBean的init方法publicabstractclassHttpServletBeanextendsHttpServletimplementsEnvironmentAware{@Overridepublicfinalvoidinit()throwsServletException{//省略部分代码//1、如下代码的作用是将Serv......
  • ScyllaDB详解
    2ScyllaDB号称下一代NoSQL,C++编写充分利用Linux底层原语优势,利用现代多核、多处理器NUMA服务器硬件,卓越性能,API兼容Cassandra和DynamoDB:支持和Cassandra一样的CQL查询语言和驱动,一样的SSTable存储格式同样支持和DynamoDB一样的JSON-style查询和驱动2.1......
  • 一文详解|支付宝小程序跳转(超详细版)
    开发过程中经常遇到支付宝小程序跳转的问题,这里总结一下支付宝小程序跳转的常见场景和方式,希望可以对大家有所帮助。话不多说,上干货!     支付宝小程序跳转的三种行为支付宝小程序跳转可以拆分为三种行为,即:外部跳转支付宝小程序支付宝小程序内部页面之间跳转......
  • Makefile基础使用和实战详解
    一、基础Makefile其实只是一个指示make程序如何为我们工作的命令文件,我们说Makefile其实是在说make。而对于项目来说,Makefile是指软件项目的编译环境。Makefile的好坏对于项目开发有些什么影响呢?设计得好的Makefile,当我们重新编译时,只需编译那些上次编译成功后修改过的......
  • Go语言代码断行规则详解
    本文深入探讨了Go语言中代码断行的各个方面,从基础概念到实际应用实践。关注【TechLeadCloud】,分享互联网架构、云服务技术的全维度知识。作者拥有10+年互联网服务架构、AI产品研发经验、团队管理经验,同济本复旦硕,复旦机器人智能实验室成员,阿里云认证的资深架构师,项目管理专业......
  • 文件上传请求头设置
    文件上传请求头设置涉及到文件上传时接口需要配置请求头:headers:{‘Content-Type’:‘multipart/form-data’}例如://导入excel数据exportfunctionimportStorage(data){returnrequest({url:'/agcloud/zhps/storage/importFile',method:'p......