contentType JSP page directive with Example

Content type in Servlets/JSP is nothing but the format of data being sent by Web server to client as response. It is received by the browser on the client system and displayed to the user. The general format and also the default is text/html, that is, either simple text or text with HTML tags (of charset ISO-8859-1 comprising all western characters which is equivalent to UTF-8). The format is specified in Servlets as response.setContentType("text.html"). The same thing is done in JSP with page directive’s contentType attribute.

contentType JSP is one of the 14 attributes, JSP page directive supports. Following is the syntax.

<%@ page contentType="text/html" %>

A few other formats are

<%@ page contentType="text/plain" %>
<%@ page contentType="image/jpeg" %>

The full format of contentType JSP can be of this form.

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

Precaution: One JSP file can set only one contentType; else it is error. That is, contentType should come only once in the JSP file.

Example on contentType JSP

Following JSP file sets the contentType to text/plain. That is, all HTML tags are treated just as plain text and not be parsed.

File Name: PageContentType.jsp

  

The contentType Attribute

<%@ page contentType="text/plain" %> This should be rendered in plain text, not as HTML.

contentType JSP

Observe the above screenshot, <B> is not parsed to bold letters and printed as it is.

<%@ page contentType="text/plain" %>

The above statement gives the syntax of using page directive attribute contentType. It is set to text/html.

In the above code, <H2> and <B> are treated simply as text but not as HTML tags. Some browsers like Internet Explorer does not support attribute contentType and parse all the tags.

Note: Write the contentType at the top of the JSP page.

Leave a Comment

Your email address will not be published.