簡體   English   中英

如何將位置標頭添加到 http 響應?

[英]How to add Location header to the http response?

我有一個 Java 項目,我正在使用 Servlet 來處理 http 請求。 我也用彈簧

當我收到創建新對象(例如帳戶)的請求時,我還想返回帶有新創建對象的 GET URL 的“位置”標頭。 例如:位置:/accounts/1000

我知道標題已添加到 Servlet 過濾器中(如果我錯了,請糾正我)

public class ApiLogFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger("apilogger");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = ((HttpServletResponse) servletResponse);
       
        httpServletResponse.addHeader( "Location","the location value");
        
        try {
          
            filterChain.doFilter(servletRequest, servletResponse);
          
        } finally {
            String queryString = httpServletRequest.getQueryString() != null ? httpServletRequest.getQueryString() : "N/A";
            String logMessage = "URL: " + httpServletRequest.getRequestURL() + ", Query String: " + queryString + ", Response Status: " + httpServletResponse.getStatus() ;
            LOGGER.info(logMessage);
        }
    }

    @Override
    public void destroy() {

    }
}

但我不明白如何從 API 獲取位置值

@RequestMapping("/accounts")
public class IgnoreRuleController {

    private AccountService accountService;

    public void setIgnoreRuleService(IgnoreRuleService ignoreRuleService) {
        this.accountService = ignoreRuleService;
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public String createAccount(@RequestBody Account account) {
        return new Gson().toJson(accountService.createAccount(account));
    }
    
}

我在這里找到了解決方案http://learningviacode.blogspot.com/2013/07/post-with-location.html

你不需要對過濾器做任何事情。 在 api 本身中:

  @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> createIgnoreRule(@RequestBody IgnoreRule ignoreRule) {
        String response = new Gson().toJson(ignoreRuleService.createIgnoreRule(ignoreRule));

        final URI location = ServletUriComponentsBuilder
                .fromCurrentServletMapping().path("/ignore_rules/{id}").build()
                .expand(ignoreRule.getId()).toUri();

        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(location);


        final ResponseEntity<String> entity = new ResponseEntity<>(response, headers, HttpStatus.CREATED);
        return entity;
    }

很簡單,你可以通過header直接拋出你的方法簽名:

@RequestMapping(value="/create-account", method = RequestMethod.POST)
@ResponseBody
public String createAccount(@RequestHeader HttpHeaders httpHeader, @RequestBody Account account) {
    var s = httpHeader.get("Location");

    System.out.println(s.get(0));
    return ...
}

實際上,您還可以傳遞包含所有內容(標題、正文...)的整個請求:

@RequestMapping(value="/create-account", method = RequestMethod.POST)
@ResponseBody
public String createAccount(HttpServletRequest httpRequest, @RequestBody Account account) {
    var s = httpRequest.getHeader("Location");

    System.out.println(s);

    return ....
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM