Servlet technology 12_HttpServletRequest class

What is the role of the HttpServletRequest class:

Every time a request enters the Tomcat server, the Tomcat server parses the requested HTTP protocol information and encapsulates it into the Request object. Then pass it to the service method (doGet and doPost) for us to use. We can obtain all requested information through the HttpServletRequest object.

Common methods of the HttpServletRequest class:

i. getRequestURI() Get the requested resource path

ii. getRequestURL() Get the requested uniform resource locator (absolute path)

iii. getRemoteHost() Get the ip address of the client

iv. getHeader() Get request header

v. getParameter() Get the requested parameter

vi. getParameterValues() Get the requested parameters (used when there are multiple values)

vii. getMethod() Get the request method GET or POST

viii. setAttribute(key, value); Set domain data

ix. getAttribute(key); Get domain data

x. getRequestDispatcher() Get the request forwarding object

Common API sample code:

package com.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 {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
//        i. getRequestURI() 获取请求的资源路径
        System.out.println("URI ==> " + req.getRequestURI());

//        ii. getRequestURL() 获取请求的统一资源定位符(绝对路径)
        System.out.println("URL ==> " + req.getRequestURL());

        /*  正常情况下,idea中
        使用localhost访问时,得到的客户端ip地址是 ===> 127.0.0.1
        使用127.0.0.1访问时,得到的客户端ip地址是 ===> 127.0.0.1
        使用真实的电脑ip访问时,得到的客户端ip地址是 ===> 真实的客户端ip地址
         */
//        iii. getRemoteHost() 获取客户端的 ip 地址
        System.out.println("客户端ip ==> " + req.getRemoteHost());

//        iv. getHeader() 获取请求头
        System.out.println("请求头User-Agent ===> " + req.getHeader("User-Agent"));

//        vii. getMethod() 获取请求的方式 GET 或 POST
        System.out.println("请求的方式:" + req.getMethod());
    }
}

operation result:
Insert picture description here

How to get request parameters:

Create a form.html

<!DOCTYPE html>
<html lang="zh_CN">
<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
        <input type="submit">
    </form>
</body>
</html>

Create a ParameterServlet.java

package com.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 {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //获取请求参数
        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));

    }
}

Of course, don't forget to configure xml.

operation result:

Insert picture description here

Solve the problem of garbled Chinese characters in post request:

Enter Chinese in the user name box, the get request is normal, and the post request is garbled :

Insert picture description here

Just use one api ( only useful before getting the parameter request )

//设置请求体的字符集为UTF-8,从而解决post请求的中文乱码问题
req.setCharacterEncoding("UTF-8");

In this way, the problem can be solved

Insert picture description here

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    //设置请求体的字符集为UTF-8,从而解决post请求的中文乱码问题
    req.setCharacterEncoding("UTF-8");
    System.out.println("---------doPost-----------");
    //获取请求参数
    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));
}

Forwarding of the request:

What is request forwarding?

Request forwarding refers to the operation of jumping from one resource to another resource after the server receives the request, called request forwarding.

Insert picture description here

Servlet1:

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

public class Servlet1 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //获取请求参数(办事的材料)
        String username = req.getParameter("username");
        System.out.println("在Servlet1(柜台1)中查看的参数(材料):" + username);

        //给材料盖一个章,并传递到Servlet2(柜台2)查看
        req.setAttribute("key1","柜台1的章");

        //问路:Servlet2(柜台2)怎么走
        /**
         * 请求转发必须要以 / 打头,斜杠表示地址为: http://ip:port/工程名/ ,映射到 idea 代码的 web 目录
         */
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2");

        //走向Servlet2
        requestDispatcher.forward(req,resp);
    }
}

Servlet2:

package com.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 Servlet2 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //获取请求参数(办事的材料)
        String username = req.getParameter("username");
        System.out.println("在Servlet2(柜台2)中查看的参数(材料):" + username);

        //查看柜台1改的章
        Object key1 = req.getAttribute("key1");
        System.out.println("柜台1是否有章:" + key1);

        //处理自己的业务
        System.out.println("Servlet2处理自己的业务");
    }
}

Features of request forwarding:

  1. The browser address bar has not changed
  2. They are a request
  3. They share the data in the Request field
  4. It can be forwarded to the WEB-INF directory (form.html cannot be deployed to the WEB-INF directory, but it can be accessed through request forwarding)
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/form.html");

The role of the base tag:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    这是web下的index.html<br/>
    <a href="a/b/c.html">a/b/c.html</a>
    <br/>
    <a href="http://localhost:8080/07_servlet/forwardC">请求转发:a/b/c.html</a>
</body>
</html>

c.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    这是web/a/b下的c.html<br/>
    <a href="../../index.html">跳回首页</a>
</body>
</html>

ForwardC.java

public class ForwardC extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("经过了ForwardC程序");
        req.getRequestDispatcher("/a/b/c.html").forward(req,resp);
    }
}

When we click the a tag in index.html to jump, the address in the address bar of the browser is:

http://localhost:8080/07_servlet/a/b/c.html

The a tag path to jump back to is:

../../index.html

All relative paths will refer to the address in the address bar of the current browser to jump when working

Then the address obtained after reference is:

http://localhost:8080/07_servlet/index.html

Correct jump path

When we use request forwarding to redirect, the address in the browser's address bar is:

http://localhost:8080/07_servlet/forwardC

The a tag path to jump back to is:

../../index.html

All relative paths will refer to the address in the address bar of the current browser to jump when working.

Then the address obtained after reference is:

http://localhost:8080/index.html

This is the wrong path!

Insert picture description here

The base tag can set which path to refer to when working with all relative paths in the current page.

Modified code:

c.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
<!--    base标签设置页面相对路径工作时参照的地址
        href属性就是参数的地址值-->
    <base href="http://localhost:8080/07_servlet/a/b/c.html">
</head>
<body>
    这是web/a/b下的c.html<br/>
    <a href="../../index.html">跳回首页</a>
</body>
</html>

Description:

  1. First of all, it will check whether there is a base tag. If there is a base tag, he will ignore the address in the browser's current address bar and refer to the value of base instead. It is equivalent to putting the address to the ../../index.htmlfront:
http://localhost:8080/07_servlet/a/b/c.html../../index.html

​ One ../offsets one folder, which is equal to

http://localhost:8080/07_servlet/index.html
  1. The last resource name (c.html) in the base tag can be omitted (remember: / cannot be omitted!)
<base href="http://localhost:8080/07_servlet/a/b/">

Relative and absolute paths in the Web:

In JavaWeb, there are two types of paths: relative paths and absolute paths :

The relative path is:

. Represents the current directory

… Indicates the upper level directory

The resource name represents the current directory/resource name

Absolute path:

http://ip:port/工程路径/资源路径

In actual development, the path uses absolute paths instead of simply using relative paths.

1. Absolute path

2. Base + relative path

The different meanings of the / slash in the web:

In the web, the / slash is an absolute path.

/ If the slash is parsed by the browser , the address obtained is: http://ip:port/ http://localhost:8080/

<a href="/">斜杠</a>

/ If the slash is parsed by the server , the address obtained is: http://ip:port/ project path http://localhost:8080/07_servlet/

  1. <url-pattern>/servlet1</url-pattern>
  2. servletContext.getRealPath(“/”);
  3. request.getRequestDispatcher(“/”);

Special case: response.sendRediect("/"); Send the slash to the browser for analysis. Get http://ip:port/

Guess you like

Origin blog.csdn.net/weixin_45024585/article/details/108905012