How many ways does SpringBoot have to get the Request object?

HttpServletRequest (Request for short) is an interface defined in the Java Servlet Specification, which is used to represent HTTP requests. It provides methods to access HTTP requests, including obtaining request parameters, request headers, request paths, etc.

The HttpServletRequest interface provides a series of methods for obtaining information about various parts of an HTTP request. Here are some commonly used methods:

  1. getRequestURI(): Get the URI (Uniform Resource Identifier) ​​of the request, that is, the path part of the request, excluding the host name, port number and context path.

  2. getMethod(): Get the method of HTTP request, such as GET, POST, PUT, etc.

  3. getParameter(String name): Get the value of the request parameter with the specified name. If there are multiple parameters with the same name, only the value of the first parameter is returned.

  4. getParameterMap(): Get a Map collection of all request parameters, where the key is the parameter name and the value is an array of parameter values.

  5. getHeader(String name): Get the value of the request header with the specified name.

  6. getHeaderNames(): Get an enumeration of the names of all request headers.

  7. getCookies(): Get all cookies in the request.

  8. getSession(): Get the session object associated with the request.

  9. getRemoteAddr(): Get the IP address of the client.

  10. getInputStream(): Get the input stream of the request, which is used to read the content of the request body.

Table of contents

1. Obtaining through request parameters

2. Get it through RequestContextHolder

3. Acquisition through automatic injection


1. Obtaining through request parameters

The principle of this method is that when the Controller starts to process the request, Spring will assign the Request object to the method parameter, and we can directly set it to the parameter to get the Request object.

@RequestMapping("/index")
@ResponseBody
public void index(HttpServletRequest request){
  // TODO
}

2. Get it through RequestContextHolder

In Spring Boot, RequestContextHolder is a tool class provided by the Spring framework for storing and accessing request context information related to the current thread in a multi-threaded environment. It is mainly used to store the information of the current request in the thread scope, so that the information can be shared and accessed in different components.

@RequestMapping("/index")
@ResponseBody
public void index(){
	ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
	HttpServletRequest request = servletRequestAttributes.getRequest();
	// TODO
}

3. Acquisition through automatic injection

@Controller
public class IndexController{

    @Autowired
    private HttpServletRequest request; 

}

Guess you like

Origin blog.csdn.net/qq_19309473/article/details/132335500