开发者

Java (JSP): repeating the contentType header in a "sub-jsp"

What happens when headers are repeated in a .jsp you include in another .jsp?

For example if example.jsp starts with this:

<?xml version="1.0" encoding="UTF-8"?>
<jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:directive.page contentType="text/html; charset=UTF-8" />

<div class="content">

<jsp:include page开发者_开发百科="support.jsp"/>
...

(it includes support.jsp)

And then support.jsp starts also with this:

<?xml version="1.0" encoding="UTF-8"?>
<jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:directive.page contentType="text/html; charset=UTF-8" />
... 

Is that a problem? Is it bad practice?

What does concretely happen when you repeat several times a header that only corresponds to one header in the resulting .html page?


From JSP Specification:

JSP.5.4 <jsp:include>

...

An included page cannot change the response status code or set headers. This precludes invoking methods like setCookie. Attempts to invoke these methods will be ignored. The constraint is equivalent to the one imposed on the include method of the RequestDispatcher class.

That is, attempt to set content type will be ignored.


The directive is translated directly to ServletResponse.setContentType call

The documentations for this method says:

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter has been called or after the response has been committed.

Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.

It seems to me that it's better to use this directive only once in the top-level JSP page, maybe even in controller servlet, but definitely not in included pages.

For pages not written in JSPX, one directive that IS useful and should be set in all JSPs that have non-ascii characters is <%@ page pageEncoding="XXXX" %>. I highly recommend it if you don't like to print \uXXXX codes all over your pages.


It's absolutely normal practice.

What you call 'headers' are just directives to jsp-compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜