The Java Object Request

A, Request and Response object objects principle

  request and response objects are created by the server for us to use.

  request object is to get request message, response message in response to the object is set.

  Schematic :

 

 

 

Two, Request object inherits architecture

  

 

 

 

Three, Request function

  1, a data acquisition request message

    (1) row data acquisition request

       Common methods:

(1) String getMethod (): Get request method 
(2) String getContextPath (): Get the virtual directory [important] 
(. 3) String getServletPath (): Get servlet path 
(4) String getQueryString (): Get get mode request parameter 
( 5) String getRequestURI (): Gets the request URI [important] 
(6) StringBuffer getRequestURL (): Gets the request of the URL of 
(7) String getProtocol (): Gets the agreement and release 
(8) String getRemoteAddr (): Gets IP client address

      Note :

      URI: Uniform Resource Identifier;

      URL: Uniform Resource Locator;

      Demo:

1 请求行数据 GET /servletDemo/demo1?name=zhangsan HTTP/1.1
2 String getMethod():          获取到 GET
3 String getContextPath():     获取到 /servletDemo
4 String getServletPath():     获取到 /demo1
5 String getQueryString():     获取到 name=zhangsan
6 String getRequestURI():      获取到 /servletDemo/demo1
7 StringBuffer getRequestURL():获取到 http://localhost/servletDemo/demo1
8 String getProtocol():        获取到 HTTP/1.1
9 String getRemoteAddr():      获取到 请求机器的IP地址

 

    

    (2)获取请求头数据

      常用方法:

 

String getHeader(String name):通过请求头的名称获取请求头的值[重要]
Enumeration<String> getHeaderNames():获取所有的请求头名称

 

  

 

    (3)获取请求体数据

        请求体:只有POST请求方式,才有请求体,在请求体重封装了POST请求的请求参数

        步骤:

        ① 获取流对象

 

BufferedReader getReader():获取字符输入流,只能操作字符数据
ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据

 

        ② 从流对象中拿数据

        Demo:

 

 1  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2         //1.获取字符流
 3         BufferedReader br = request.getReader();
 4 
 5         //2.读取数据
 6         String line = null;
 7         while((line = br.readLine()) != null) {
 8             System.out.println(line);   // 请求参数username=zs&password=abc
 9         }
10     }

 

 

 

 

  2、其他功能

    (1)获取请求参数通用方式:无论是get方式还是post请求方式都可以使用下列方法来获取请求参数

        常用方法

(1)String getParameter(String name):根据参数名称获取参数值    username=zs&password=abc
(2)String[] getParameterValues(String name):根据参数名称获取参数值的数组  hobby=java&hobby=python
(3)Enumeration<String> getParameterNames():获取所有请求的参数名称(相当于Iterator)
(4)Map<String,String[]> getParameterMap():获取所有参数的map集合,可以根据键(参数名)获取值(参数值)

          注意

        ① get方式:tomcat 8 已经将 get 方式乱码问题解决了

        ② post 方式:获取中文会产生乱码

         解决方式:在获取参数前,设置 request 的编码与页面编码一致即可

request.setCharacterEncoding("utf-8");

  

    (2)请求转发

    (3)

    (4)

    (5)

    (6)

  3、

四、

五、

六、

七、

八、

九、

Guess you like

Origin www.cnblogs.com/niujifei/p/11619202.html