springboot获取request、response的三种方法

方法1:

ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

HttpServletRequest request =servletRequestAttributes.getRequest();

HttpServletResponse response = servletRequestAttributes.getResponse();

例如:
/**
     * 新建工位
     *
     * @param stationDto
     * @return
     */
    @RequestMapping(value = "/create")
    @ResponseBody
    public ResponseEntity create(@RequestBody @Valid StationDto stationDto) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UserLoginInfoDto userLoginInfoDto = (UserLoginInfoDto) request.getAttribute(USER_LOGIN_INFO);
        stationDto.setCreateUser(userLoginInfoDto.getUserName());
        StationDto stationDto1 = stationService.create(stationDto);
        return ResponseEntity.ok(Result.success(stationDto1));
    }

方法2

public String center(HttpServletRequest request,HttpServletResponse response) {...}


@GetMapping(value = "")
public String center(HttpServletRequest request,HttpServletResponse response) {
    //...
}

方法3

@Autowired
private HttpServletRequest request;

@Autowired
private HttpServletRequest myHttpRequest;
 
@Autowired
private HttpServletResponse myHttpResponse;
 
@GetMapping(value = "")
public String center() {
    //refer to myHttpRequest or myHttpResponse
}

你可能感兴趣的:(springboot获取request、response的三种方法)