如何拦截Content-Type头含addHeader的请求?doFilter使用存疑
Hey there! Let's tackle this request blocking problem properly. Using a JSP to handle request interception isn't the best practice—Java Web has a dedicated component for this: Filters. They run before the request reaches your Servlet/JSP, making them ideal for centralized, reusable request handling.
Step 1: Create a Filter Class
Filters implement the javax.servlet.Filter interface, where you'll override the doFilter method to check and block requests. Here's a complete example:
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; // Annotate to intercept all requests (adjust URL pattern as needed, e.g., "/api/*" or "*.jsp") @WebFilter("/*") public class ForbiddenHeaderFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { // Optional: Initialize resources or read config parameters here } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Cast to HTTP-specific objects to access headers HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // Get the Content-Type header (handle null cases to avoid NPE) String contentType = httpRequest.getHeader("Content-Type"); // Check if the header contains "addHeader" if (contentType != null && contentType.contains("addHeader")) { // Block the request: return 403 Forbidden error httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Request blocked: Forbidden Content-Type header detected"); System.out.println("Blocked request with Content-Type containing 'addHeader'"); return; // Stop processing, don't pass the request further } // If header is safe, pass the request to the next filter or target resource chain.doFilter(request, response); } @Override public void destroy() { // Optional: Clean up resources here } }
Key Details to Note:
- @WebFilter Annotation: This is a Servlet 3.0+ feature that eliminates the need for XML configuration. Use
"/*"to intercept all requests, or narrow it down (e.g.,"*.jsp"for only JSP requests). - Null Check: Always check if
contentTypeis null first—some requests might not include a Content-Type header, which would cause aNullPointerExceptionif you skip this. - Blocking Logic:
sendError()sends an HTTP 403 status code to the client. You could also usesendRedirect()to send users to a custom error page if needed. - Chain.doFilter(): This line is critical for passing valid requests to their intended destination (your Servlet/JSP). Without it, all requests would be blocked!
If You Must Use JSP (Not Recommended)
If you absolutely need to handle this in a JSP (though it's not ideal for centralized logic), you can modify your existing code to stop request processing:
<% String contentType = request.getHeader("Content-Type"); if (contentType != null && contentType.contains("addHeader")) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Request blocked"); return; // Stop executing the rest of the JSP } %> <!-- Your normal JSP content goes here -->
This approach works but requires duplicating code across every JSP, which is hard to maintain. Filters are always the better choice for cross-cutting concerns like request blocking.
内容的提问来源于stack exchange,提问作者kadir

