spring boot獲取request


1. Controller中

1.1 通過靜態方法獲取

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

但我在使用過程中發現遇到了一個警告

Method invocation 'getRequest' may produce 'java.lang.NullPointerException' less... (Ctrl+F1)
Inspection info: This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report NullPointerException (NPE) errors that might be produced.
More complex contracts can be defined using @Contract annotation, for example:
@Contract(", null -> null") — method returns null if its second argument is null @Contract(", null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise @Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it
The inspection can be configured to use custom @Nullable
@NotNull annotations (by default the ones from annotations.jar will be used)

如此使用可能會造成空指針異常,所以建議添加Objects.requireNonNull,如果為空,拋出異常。

HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

附Objects.requireNonNull源碼

public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

1.2 通過參數直接獲取

在參數上添加后,springboot會幫你綁定,之后可以直接使用

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

1.3 自動注入

通過@Autowired自動注入,這樣就不用每個方法都寫了

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

2.controller以外部分

見1.1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM