英文:
Is there a way in spring boot to override a request header on HttpServletRequest?
问题
我试图验证当用户没有提供内容类型标头作为标头时,我想将其默认为HttpServletRequest
上的application/json,这是否可能?我没有看到任何适合的方法。
英文:
I'm trying to validate when the user doesn't provide a content-type header as a header, I want to default it as application/json on the HttpServletRequest
, is this possible? I don't see any methods that would suit that.
答案1
得分: 1
创建一个新的Servlet过滤器,在你遇到问题的那个过滤器之前应用。在这个过滤器中,你不要将原始的 request
实例传递给过滤器链,而是将其包装在一个 jakarta.servlet.http.HttpServletRequestWrapper
中,你可以扩展它以提供默认的头信息,如果原始请求中缺少这样的头信息。
大致如下所示:
public class HeaderDefaultsRequestWrapper extends HttpServletRequestWrapper {
private final Map<String, String> headerDefaults;
public HeaderDefaultsRequestWrapper(HttpServletRequest request, Map<String, String> headerDefaults) {
super(request);
this.headerDefaults = headerDefaults;
}
@Override
public String getHeader(String name) {
String header = super.getHeader(name);
if (header == null) {
// 注意这里的头部大小写
return headerDefaults.get(name);
}
return header;
}
}
还要确保覆盖 getHeaderNames()
和其他方法,以创建一个一致的扩展该包装器类。
英文:
Create a new servlet filter that is applied before the one which troubles you. In this filter you do not pass down the original request
instance the filter chain but instead wrap it in a jakarta.servlet.http.HttpServletRequestWrapper
that you extend to provide your default headers if the original is missing such a header.
Something along the lines of:
public class HeaderDefaultsRequestWrapper extends HttpServletRequestWrapper {
private final Map<String, String> headerDefaults;
public HeaderDefaultsRequestWrapper(HttpServletRequest request, Map<String, String> headerDefaults) {
super(request);
this.headerDefaults = headerDefaults;
}
@Override
public String getHeader(String name) {
String header = super.getHeader(name);
if (header == null) {
// Also mind header casing here
return headerDefaults.get(name);
}
return header;
}
}
Also be sure to override getHeaderNames()
and other stuff to create a consistent extension of that wrapper class.
答案2
得分: 0
你可以明确提到请求头并验证相同
例如:
@GetMapping("/action")
public ResponseEntity<String> doAction(@RequestHeader("Content-Type") String headerValue) {
if (!headerValue.equals(MediaType.APPLICATION_JSON_VALUE)) {
// 抛出异常
}
return ResponseEntity.ok("Ok!");
}
英文:
You can explicitly mention request header and validate the same
e.g.
@GetMapping("/action")
public ResponseEntity<String> doAction(@RequestHeader("Content-Type") String headerValue) {
if (!headerValue.equals(MediaType.APPLICATION_JSON_VALUE)) {
// Throw exception
}
return ResponseEntity.ok("Ok!");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论