Springboot built-in object

Programmer light 2022-02-13 07:58:46 阅读数:681

springboot built-in built object

Web Built in objects mainly include

    request

    response

    session

    servletContext

   Customized built-in objects for each template engine ( Tool class )

session、servletContext Both can pass request Object

Get built-in objects by injecting method parameters

@RestController
@RequestMapping("/innerObject")
public class InnerObjectAction {
@RequestMapping("/get")
public Map<String, Object> getObjects(HttpServletRequest request,
HttpServletResponse response, HttpSession session) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("【request】 contextPath", request.getContextPath());
map.put("【response】 encoding", response.getCharacterEncoding());
map.put("【session】 sessionId", session.getId());
map.put("【servletContext】 servletName", request.getServletContext().getVirtualServerName());
map.put("【servletContext】 initParam", request.getServletContext().getInitParameter("message"));
return map;
}
}
 stay application.properties Set in file servlet Initialize parameters :
server.servlet.context-parameters.message= hello SpringBoot !!!

  Start project , visit :http://localhost:8888/innerObject/get It is found that all built-in objects can be obtained normally :

adopt ServletRequestAttributes obtain  

 @RequestMapping("/getObjects")
public Map<String, Object> getObjects() {
// Get attribute information
ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
Map<String, Object> map = new LinkedHashMap<>();
map.put("【request】 contextPath", request.getContextPath());
map.put("【response】 encoding", response.getCharacterEncoding());
map.put("【session】 sessionId", request.getSession().getId());
map.put("【servletContext】 servletName", request.getServletContext().getVirtualServerName());
map.put("【servletContext】 initParam", request.getServletContext().getInitParameter("message"));
return map;
}

The requested information will be sent at each request request The object is encapsulated as RequestAttributes Save in ThreadLocal in , And by RequestContextHolder Class can get RequestAttributes, and RequestAttributes It's an interface , To convert it to ServletRequestAttributes Before you can take it out request object .response The object is the same .

copyright:author[Programmer light],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130758442833.html