You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拦截Content-Type头含addHeader的请求?doFilter使用存疑

How to Block Requests with "addHeader" in Content-Type Header

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 contentType is null first—some requests might not include a Content-Type header, which would cause a NullPointerException if you skip this.
  • Blocking Logic: sendError() sends an HTTP 403 status code to the client. You could also use sendRedirect() 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 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:08:06