简体   繁体   中英

Making JSP page not set the response content-type

Is it possible to make JSP pages not set any content type on response? In my setup, JSP doesn't directly generate the response, but rather an intermediate presentation, which is then processed by additional Java code that creates HTML or JSON based on that. So, can I somehow make JSP not set content-type on the response and leave it to the intermediate code? If I just remove contentType="..." in a JSP, it still defaults to text/html .

You could make it ignore the content type that the JSP page sets. Would that be good enough?
How are you doing the plumbing?

The basic idea would be to implement a ServletResponseWrapper, override the call to setContentType, and then use a filter to pass this response to the JSP rather than the real one.

ResponseWrapperToIgnoreContentType.java

import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;

public class ResponseWrapperToIgnoreContentType extends ServletResponseWrapper{

    public ResponseWrapperToIgnoreContentType(final ServletResponse response) {
        super(response);        
    }

    @Override
    public void setContentType(final String type) {
        System.out.println("Ignoring call to set the content type to : " + type);
    }
}

Filter to apply it:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ResponseContentTypeFilter implements Filter{

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, new ResponseWrapperToIgnoreContentType(response));
    }

    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {

    }

}

EDIT: Just spotted a flaw in my logic. The content type is required to be set before you can call response.getWriter(), so that it can use the right character encoding. Dunno if this would affect you or not.

Nope.

Why don't you store the preferred content-type in the class you're creating and generate accessors for it and have the JSP get it from there?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM