检测 html 文件时 HttpServletResponse 内容类型为空
HttpServletResponse content type null when detecting html file
我正在尝试实施 Java servlet 过滤器,它会修改 html 响应。
doFilter
我的过滤器 class 的方法看起来像这样:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (filterConfig == null) {
return;
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String contentType = res.getContentType();
if (contentType != null && contentType.contains("text/html")) {
chain.doFilter(req, res);
// do some modification
}
}
对于每一个回复,我都试图弄清楚它是否是 HTML。如果是这样,我做了一些修改,但是我有以下问题:请求jsf文件时,res.getContentType()
returns null
(res.getHeader("Content-Type")
also return s null
)。在我的浏览器的开发者工具中,我可以看到 'Content-Type' header 的值为 'text/html; charset=UTF-8',但为什么 res.getContentType()
return null
在那种情况下呢?
是否有任何其他方法来检测过滤器中的 HTML 响应?
编辑我在 if 子句中添加了 chain.doFilter(req, res)
调用。
由于 JSF 使用 servlet,您只能检查它在链之后生成的内容(您似乎希望它在您的过滤器之前执行,但事实并非如此)。这样做的原因是完整的过滤器链总是在before servlets 执行,总是,见
- Is doFilter() executed before or after the Servlet's work is done?
- Servlet vs Filter
- What is the use of filter and chain in servlet?
这意味着在您的 doFilter(...)
中,您只有在 在 代码中的 chain.doFilter(..)
之后访问它才能访问响应,如在首先link。
因此,除非过滤器创建内容(它不应该是 iirc,至少不是真正的内容),响应上的内容类型将始终 在调用 chain.doFilter()
之前为 null(除非过滤器例如创建了 authentication/authorisation 失败响应)。
有效地执行您的代码
String a=null;
if (a != null || or a.equals("b") {
doThing();
}
因此您似乎有一个 http://www.xyproblem.info,因此您必须重新考虑您的设计。 (你想达到什么目的)
我正在尝试实施 Java servlet 过滤器,它会修改 html 响应。
doFilter
我的过滤器 class 的方法看起来像这样:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (filterConfig == null) {
return;
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String contentType = res.getContentType();
if (contentType != null && contentType.contains("text/html")) {
chain.doFilter(req, res);
// do some modification
}
}
对于每一个回复,我都试图弄清楚它是否是 HTML。如果是这样,我做了一些修改,但是我有以下问题:请求jsf文件时,res.getContentType()
returns null
(res.getHeader("Content-Type")
also return s null
)。在我的浏览器的开发者工具中,我可以看到 'Content-Type' header 的值为 'text/html; charset=UTF-8',但为什么 res.getContentType()
return null
在那种情况下呢?
是否有任何其他方法来检测过滤器中的 HTML 响应?
编辑我在 if 子句中添加了 chain.doFilter(req, res)
调用。
由于 JSF 使用 servlet,您只能检查它在链之后生成的内容(您似乎希望它在您的过滤器之前执行,但事实并非如此)。这样做的原因是完整的过滤器链总是在before servlets 执行,总是,见
- Is doFilter() executed before or after the Servlet's work is done?
- Servlet vs Filter
- What is the use of filter and chain in servlet?
这意味着在您的 doFilter(...)
中,您只有在 在 代码中的 chain.doFilter(..)
之后访问它才能访问响应,如在首先link。
因此,除非过滤器创建内容(它不应该是 iirc,至少不是真正的内容),响应上的内容类型将始终 在调用 chain.doFilter()
之前为 null(除非过滤器例如创建了 authentication/authorisation 失败响应)。
有效地执行您的代码
String a=null;
if (a != null || or a.equals("b") {
doThing();
}
因此您似乎有一个 http://www.xyproblem.info,因此您必须重新考虑您的设计。 (你想达到什么目的)