Dónal
Dónal

Reputation: 187369

scriptless JSP

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

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

Upvotes: 1

Views: 2321

Answers (3)

Will Hartung
Will Hartung

Reputation: 118704

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.

Upvotes: 2

myplacedk
myplacedk

Reputation: 1564

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.

Upvotes: 0

AlexJReid
AlexJReid

Reputation: 1601

<%@ 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.

Upvotes: 2

Related Questions