简体   繁体   中英

Cannot set Content-Type / MIME-type in java servlet

I'm using the following filter, explicitly setting the content-type for the response to application/json:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    filterChain.doFilter(servletRequest, servletResponse);
}

It does not work, however, and the content-type when requested in a browser is text/html. The other headers work fine.

I realize this is old. I've had this issue and my workaround is:

    resp.setHeader("Content-Disposition","attachment; filename="+fname);

See: http://archive.oreilly.com/pub/a/onjava/excerpt/jebp_3/index3.html

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