HttpServletRequest class and HttpServletResponse class in javaWeb-4-Tomcat server

table of Contents

1、HttpServletRequest 类

1.1 The role of HttpServletRequest class

1.2 Common methods of the HttpServletRequest class-source code structure diagram

1.3 HttpServletRequest class-code demonstration of some methods-project structure

1.3.1 Writing Servlet Processor-RequestApiServlet extends HttpServlet 

1.3.2 web.xml configuration file

1.3.3 Chrome browser sends client request

1.3.4 Tomcat server response

2. How to get the request parameters sent by the client-form request

2.1 HttpServletRequest class-get request parameter code demo-project structure

2.1.1 Write a Servlet processor-pay attention to the Chinese garbled problem of the request body in POST request-UTF-8

2.1.2 web.xml configuration file

2.1.3 Writing front-end pages

2.1.4 Simulate front-end page request

2.1.5 Tomcat server response result

3. Request forwarding

3.1 What is request forwarding

3.2 Characteristics of request forwarding

3.3 Request forwarding code demo-project structure

3.3.1 Write two Servlet processors: Servlet1 and Servlet2

3.3.2 Configure the access path of the servlet processor in the web.xml file

3.3.3 A request from the front end (before and after this request, the address in the address bar will not change)

3.3.4 The result of the back-end processing this request

4. The role of the Base tag

5. Relative and absolute paths in the Web

6. The meaning of the / slash in the Web

7、HttpServletResponse 类

7.1 The role of the HttpServletResponse class

7.2 Common methods of the HttpServletResponse class-source code structure diagram

7.3 HttpServletRepose object: the stream needs to be used when passing data to the client

7.4 HttpServletRepose object: how to pass data to the client

7.5 HttpServletRepose object: request redirection and its characteristics and implementation methods

7.6 HttpServletRepose object: code demonstration of request redirection-project structure

7.6.1 Writing Servlet Dynamic Resources-ResponseServlet1 Object and ResponseServlet2 Object

7.6.2 Configure the access path of Servlet resources in the web.xml file

7.6.3 The front-end browser initiates a request

7.6.4 The back-end Tomcat container handles front-end requests

8. Servlet learning appendix

1、HttpServletRequest 类

1.1 The role of HttpServletRequest class

Every time a request comes Tomcat server, the Tomcat server will request the information sent to the HTTP protocol  parsing well encapsulated Request object , and then passed to the service () method (call doGet () or doPost () method) for programming Personnel use, programmers can obtain all the requested information through the HttpServletRequest object.

1.2 Common methods of the HttpServletRequest class-source code structure diagram

(1) getRequestURI(): get the requested resource path
(2) getRequestURL(): get the absolute path of the request
(3) getRemoteHost(): get the IP address of the client
(4) getHeader(): get the request header
(5) getParameter (): Get request parameters
(6) getParameterValues(): Get request parameters (used when multiple values ​​are used)
(7) getMethod(): Get the request method (GET or POST)
(8) setAttribute(key, value): set Domain data
(9) getAttribute(key): get domain data
(10) getRequestDispatcher(): get request forwarding object

1.3 HttpServletRequest class-partial method code demonstration-project structure

1.3.1 Writing Servlet Processor-RequestApiServlet extends HttpServlet 

package com.wind.servlet;

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

public class RequestApiServlet extends HttpServlet {

    private static final long serialVersionUID = -8497166361222348250L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet done.");
        //(1)getRequestURI():获取请求的资源路径
        System.out.println("URI=" + request.getRequestURI());
        //(2)getRequestURL():获取请求的绝对路径
        System.out.println("URL=" + request.getRequestURL());
        //(3)getRemoteHost():获取客户端的IP地址
        System.out.println("客户端IP=" + request.getRemoteHost());
        //(4)getHeader():获取请求头
        System.out.println("Header=" + request.getHeader("User-Agent"));
        //(5)getMethod():获取请求的方式(GET或POST)
        System.out.println("Method=" + request.getMethod());
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost done.");
    }
}

1.3.2 web.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>RequestApiServlet</servlet-name>
        <servlet-class>com.wind.servlet.RequestApiServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>RequestApiServlet</servlet-name>
        <url-pattern>/requestApiServlet</url-pattern>
    </servlet-mapping>

</web-app>

1.3.3 Chrome browser sends client request

1.3.4 Tomcat server response

2. How to get the request parameters sent from the client-form request

2.1 HttpServletRequest class-get request parameter code demo-project structure

2.1.1 Write a Servlet processor-pay attention to the Chinese garbled problem of the request body in POST request-UTF-8

package com.wind.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.util.Arrays;

/**
 * 测试在服务器端获取从客户端发出请求的请求参数。
 */
public class ParameterServlet extends HttpServlet {

    private static final long serialVersionUID = -6845943440777584931L;

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("==doGet方法执行了==");
        if (request != null) {
            //获取请求参数
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String[] hobby = request.getParameterValues("hobby");
            System.out.println("用户名=" + username);
            System.out.println("密码" + password);
            System.out.println("爱好=" + Arrays.asList(hobby));
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("==doPost方法执行了==");
        if (req != null) {
            //解决post请求中请求体的中文乱码问题
            req.setCharacterEncoding("UTF-8");
            //获取请求参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String[] hobby = req.getParameterValues("hobby");
            System.out.println("用户名=" + username);
            System.out.println("密码" + password);
            System.out.println("爱好=" + Arrays.asList(hobby));
        }
    }
}

2.1.2 Configure Servlet dynamic resource and access path in web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>ParameterServlet</servlet-name>
        <servlet-class>com.wind.servlet.ParameterServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ParameterServlet</servlet-name>
        <url-pattern>/parameterServlet</url-pattern>
    </servlet-mapping>

</web-app>

2.1.3 Writing the front-end page: from.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/07_servlet/parameterServlet" method="GET">
    用户名:<input type="text" name="username"><br/>
    密码:<input type="password" name="password"><br/>
    兴趣爱好:<input type="checkbox" name="hobby" value="cpp">C++
    <input type="checkbox" name="hobby" value="Java">Java
    <input type="checkbox" name="hobby" value="JS">JavaScript<br/>
    <input type="submit">
</form>
</body>
</html>

2.1.4 Simulate front-end page request

http://localhost:8080/07_servlet/parameterServlet?username=111&password=222&hobby=Java&hobby=JS

2.1.5 Tomcat server response result

3. Request forwarding

3.1 What is request forwarding

Request forwarding: refers to the process of jumping from one Servlet resource to another Servlet resource after the server receives the client's request, which is called request forwarding.

3.2 Characteristics of request forwarding

3.3 Request forwarding code demo-project structure

3.3.1 Write two Servlet processors: Servlet1 and Servlet2

package com.wind.servlet;

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

/**
 * Servlet1处理器
 */
public class Servlet1 extends HttpServlet {

    private static final long serialVersionUID = 7270974308321925570L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数(查看办事的材料)
        String username = request.getParameter("username");
        System.out.println("在Servlet1(柜台1)中查看参数(材料):" + username);
        //2.给材料盖章
        request.setAttribute("key1", "柜台1的章");
        //3.获得通向Servlet2的路径(即:请求转发对象)
        //注意:参数必须以斜杠打头,斜杠代表 http://localhost:8080/工程名/,对应IDEA代码的web目录
        //请求可以转发到WEB-INF目录下,比如:request.getRequestDispatcher("/WEB-INF/from.html");
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servlet2");
        //4.通过得到的路径走向Servlet2(柜台2)
        //forward方法将当前资源的request和response转发到该requestDispatcher指定的资源中去,
        //从而使得Servlet2中获取到的最初的request和response与Servlet1保持一致
        requestDispatcher.forward(request, response);
    }
}
package com.wind.servlet;

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

/**
 * Servlet2处理器
 */
public class Servlet2 extends HttpServlet {

    private static final long serialVersionUID = 8273702373386138440L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数(查看办事的材料)
        String username = request.getParameter("username");
        System.out.println("在Servlet2(柜台2)中查看参数(材料):" + username);
        //2.查看是否有柜台1的章
        Object key1 = request.getAttribute("key1");
        System.out.println("柜台1的章为:" + key1);
        //3.处理Servlet2自己的业务
        System.out.println("Servlet2处理业务结束。整个请求处理结束了(从前端发起一次请求,到后端由两个Servlet处理器处理业务)。");
    }
}

3.3.2 Configure the access path of the servlet processor in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>Servlet1</servlet-name>
        <servlet-class>com.wind.servlet.Servlet1</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Servlet2</servlet-name>
        <servlet-class>com.wind.servlet.Servlet2</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Servlet1</servlet-name>
        <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Servlet2</servlet-name>
        <url-pattern>/servlet2</url-pattern>
    </servlet-mapping>

</web-app>

3.3.3 A request from the front end (before and after this request, the address in the address bar will not change)

3.3.4 The result of the back-end processing this request

It can be concluded that the content of the address bar does not change, but the page automatically jumps (accessed) to the request forwarding object Servlet2, that is, the page of http://localhost:8080/07_servlet/Servlet2 is displayed.

4. The role of the Base tag

https://blog.csdn.net/weixin_49343190/article/details/107878144

Code example: 1. Create a folder in the web directory, create a folder in b, create c.html

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    这是a下的b下的c.html<br/>
    <a href="../../index.html">跳到web下的index.html</a>
</body>

Code sample: 2. Create index.html in the web directory

<head>							
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    这是web下的index.html页面<br/>
    <a href="a/b/c.html">跳转到a下的b下的c.html</a>
</body>

[Analysis] When the c.html page is ready to be clicked to jump, the address bar of the browser is http://localhost:63342/FirstWeb/MyTest/web/a/b/c.html,
jump to index.html The path of the a tag on the page is.../.../index.html, all relative paths will refer to the address in the current browser address bar to jump when jumping, and the jump path is http://localhost: 63342/FirstWeb/MyTest/web/a/b/c.html.../.../index.html, after offsetting, the remaining path is http://localhost:63342/FirstWeb/MyTest/web/index.html, the path Correct, the jump was successful.

Code example: 1. Create a folder in the web directory, create a folder in b, create c.html

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    这是a下的b下的c.html<br/>
    <a href="../../index.html">跳到web下的index.html</a>
</body>

Code sample: 2. Create this Forward class under src and configure it in web.xml

public class Forward extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("a/b/c.html").forward(request,response);
    }
}

Code example: 3. Create index.html in the web directory

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    这是web下的index.html页面<br/>
    <a href= http://localhost:8080/MyTest/Forward>请求转发:a/b/c.html</a>
</body>

Analysis: Enter http://localhost:63342/FirstWeb/MyTest/web/index.html in the address bar, click and successfully jump to http://localhost:8080/MyTest/Forward, the page at this time is

Insert picture description here

After clicking it, it cannot be redirected. According to the above reasons, the address to be redirected is http://localhost:8080/MyTest/Forward…/…/index.html, after offsetting, it is http://localhost:8080/…/index. html, this is the wrong path, so the jump failed.

The solution is as follows: The base tag  can set all relative paths in the current page to refer to the specified path to jump when jumping, and set the specified path in the href attribute.

Code example: 4. Modify the above c.html file to the following to successfully jump

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--base标签写在<title>标签之后-->
    <base href="http://localhost:8080/MyTest/a/b/">
</head>
<body>
    这是a下的b下的c.html<br/>
    <a href="../../index.html">跳到web下的index.html</a>
</body>

Note: Absolute paths are used in actual development, rather than simply using relative paths.

5. Relative and absolute paths in the Web

6. The meaning of the / slash in the Web

7、HttpServletResponse 类

7.1 The role of the HttpServletResponse class

(. 1) Request object: every time a Tomcat server HTTP request comes in, the Tomcat server will request the information sent to the HTTP protocol  parsing well encapsulated Request object in

Then pass it to the service() method (call doGet() or doPost() method) for programmers to use, programmers can get all the requested information through the HttpServletRequest object.

(2) Response object: Every time an HTTP request enters the Tomcat server, the Tomcat server will create a Response object and pass it to the Servlet program.

HttpServletResponse represents all the response information (HttpServletRequest represents the information sent by the request), and the information that the server wants to return to the client can be set through the HttpServletResponse object.

7.2 Common methods of the HttpServletResponse class-source code structure diagram

7.3 HttpServletRepose object: the stream needs to be used when passing data to the client

Description of the two output streams:

(1) Byte stream: getOutputStream(); often used to download (transfer) binary data.

(2) Character stream: getWriter(); is often used to return a string.

(3) Note: For the same HttpServletResponse object, two streams cannot be used at the same time, only one of the two can be selected. Otherwise, an error will be reported as shown in the figure below:

7.4 HttpServletRepose object: how to pass data to the client

public class ResponseIOServlet extends HttpServlet {

    private static final long serialVersionUID = -48758485117522083L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //默认支持的字符集=ISO-8859-1
        System.out.println("默认支持的字符集=" + response.getCharacterEncoding());
        /**
         *
         * //1.1设置服务器端使用UTF-8字符集
         * response.setCharacterEncoding("UTF-8");
         * //1.2通过响应头,设置客户端使用UTF-8字符集
         * response.setHeader("Content-type", "text/html; charset=UTF-8");
         */
        //1.为了防止中文乱码问题,在获取流对象之前调用此方法,功能:同时设置服务器和客户端使用UTF-8字符集
        response.setContentType("text/html; charset=UTF-8");
        //2.获取流对象
        PrintWriter writer = response.getWriter();
        //3.返回给客户端中文数据和英文数据
        writer.write("HttpServletResponse return string to chrome...");
        writer.write("<br/>");
        writer.write("HttpServletResponse return 上海 to chrome...");
    }
}

7.5 HttpServletRepose object: request redirection and its characteristics and implementation methods

(1) Request forwarding: refers to the process of jumping from one Servlet resource to another Servlet resource after the server receives the client's request, which is called request forwarding.

(2) Request redirection : refers to the client sending a request to the server, and then the server notifies the client to access its new address (the previous address may be discarded). This process is called request redirection.

Two ways to request redirection:

7.6 HttpServletRepose object: code demonstration of request redirection-project structure

7.6.1 Writing Servlet Dynamic Resources-ResponseServlet1 Object and ResponseServlet2 Object

package com.wind.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 演示重定向使用的动态资源-ResponseServlet1
 */
public class ResponseServlet1 extends HttpServlet {

    private static final long serialVersionUID = 8523638183221949052L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        System.out.println("首先访问到了ResponseServlet1...");
        //1.设置响应状态码302
        response.setStatus(302);
        //2.设置响应头高速客户端新的资源访问地址在哪里
        response.setHeader("Location", "http://localhost:8080/07_servlet/responseServlet2");
    }
}
package com.wind.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 重定向测试使用的动态资源-ResponseServlet2
 */
public class ResponseServlet2 extends HttpServlet {

    private static final long serialVersionUID = -2816601585770886777L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        System.out.println("通过重定向,访问到了ResponseServlet2...");
        response.getWriter().write("通过重定向,访问到了ResponseServlet2,它做完了业务操作...");
    }
}

7.6.2 Configure the access path of Servlet resources in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>ResponseServlet1</servlet-name>
        <servlet-class>com.wind.servlet.ResponseServlet1</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ResponseServlet2</servlet-name>
        <servlet-class>com.wind.servlet.ResponseServlet2</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ResponseServlet1</servlet-name>
        <url-pattern>/responseServlet1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ResponseServlet2</servlet-name>
        <url-pattern>/responseServlet2</url-pattern>
    </servlet-mapping>

</web-app>

7.6.3 The front-end browser initiates a request

7.6.4 The back-end Tomcat container handles front-end requests

8. Servlet learning appendix

 

 

Guess you like

Origin blog.csdn.net/cmm0401/article/details/111420979