简体   繁体   中英

Include JSP page ignores custom headers

I have a servlet that includes a JSP page along with custom header:

    rsp.setStatus(HttpServletResponse.SC_OK);
    rsp.setContentType("text/html");
    rsp.addHeader("X-MyHeader", "Test");
    RequestDispatcher rd = req.getRequestDispatcher("MyPage.jsp");
    if ( rd != null )
        rd.include( req, rsp );

The problem is, the custom header is not included in the output stream.

I understand that an included service cannot add or change headers, that such changes are ignored, but in this case it's not an included service that's attempting to add a header, it's the service doing the include, and it's a .jsp page that's being included not a service.

How can I include a custom header in the outer service (there's actually only one service here) while also including a .jsp page?

You see, JSP pages get coded and compiled as Servlets. So a JSP page is basically a Servlet in disguise, so by invoking it you actually redirect to a different Servlet. If you want to change the headers within the JSP you can do it like this:

<%
response.setHeader("X-MyHeader", "Test");
%>

I you only want to include some markup in your original Servlet I suggest you store in a text file and then append the content of the file to the Servlet's outpustream.

There are two issues at play. The response header did not appear in the output stream because the service was already included via a <jsp:include page=service...> action element, and because the output stream writer was obtained before setting the header.

The complete original JSP page consists of only 3 lines:

<%@ page contentType="text/html; charset=UTF-8">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="/myservice"/>

As you can see, that page includes the service, which subsequently executes:

PrintWriter w = rsp.getWriter();
...
rsp.setStatus(HttpServletResponse.SC_OK);
rsp.setContentType("text/html");
rsp.addHeader("X-MyHeader", "Test");
RequestDispatcher rd = req.getRequestDispatcher("MyPage.jsp");
if ( rd != null )
    rd.include( req, rsp );

Not only are there nested pages, but once the output stream writer is obtained, the Headers cannot be updated. Either condition would cause the problem.

See Why can't HttpServletResponse Headers be updated AFTER getWriter() is called? for more information.

The solution that worked for me was to include the header from the original JSP page (bypassing both problems):

<%@ page contentType="text/html; charset=UTF-8">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<% response.setHeader("X-MyHeader", "Test"); %>
<jsp:include page="/myservice"/>

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