tags:

views:

372

answers:

3

Hi,

Is there any way to do the equivalent of the following in a JSP without using scriptlet?

<% response.setContentType("text/plain");  %>

I can't simply use

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

because I need to set the content-type in 2 places (each in a different branch of a ) and the JSP compiler will only allow one such directive.

Also, I can't write two separate JSPs and forward to one or the other in a servlet because the JSP is triggered by the container when an authentication failure occurs.

Cheers, Don

+1  A: 
<%@ page language="java" contentType="text/plain" %>

Edit:

If you need to set the MIME type conditionally, you could use

<% 
if( branch condition ) { 
  response.setContentType("text/plain");
} else {
  response.setContentType("text/html"); 
}
%>

Obviously the above is a scriptlet which goes against the original question. Is there a particular reason for not wanting to use a scriptlet?

A better approach may be to perform the branch logic in a servlet and forward the request to a JSP which only handles the display. You may choose to use two separate JSPs, one for each content type, if the content itself differs.

AlexJReid
Sorry, I forgot to mention why I can't use this, I've updated the question
Don
There's no particular reason for not wanting to use scriptlet apart from the fact that it's considered a bad practice.
Don
A: 

A text/plain-response and a text/html-response sound like two very different responses with very little in common.

Create 2 JPS's, and branch in the servlet in stead.

If they do have common elements, you can still use includes.

myplacedk
+1  A: 

The easiest way is to create a Tag File tag that can do this, then use that.

Create the file "setMimeType.tag" in your WEB-INF/tags directory.

<%@tag description="put the tag description here" pageEncoding="UTF-8"%>
<%@ attribute name="mimeType" required="true"%>
<%
    response.setContentType(jspContext.findAttribute("mimeType"));
%>

Then, in your JSP add this to the header:

<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

Then in your JSP you can do:

<t:setMimeType mimeType="text/plain"/>

Yes, the Tag File is NOT script free, but the actual JSP page IS. You can argue I'm splitting hairs, but I'd disagree, as I think tag files are the perfect medium to put things like scripting, as they provide a nice bit on encapsulation and abstraction. Also, the only other solution is to write your own JSP Tag handler in Java, which is insane for something as simple as this.

Requires JSP 2.0, but I find JSP Tag Files to be a great boon to JSP development.

Will Hartung