Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a JSP, how can I dynamically set the contentType?

I have a very simple JSP that looks like this:

<%@ page contentType="application/json" %>${actionBean.response}

actionBean.response returns a String. Sometimes that string is json which has a contentType of "application/json" but sometimes that string is jsonp which has a contentType of "application/javascript". But I can't figure out how to dynamically set the value of the contentType.

  1. I've tried using <c:choose> around the contentType but it gives me an error saying that I can't set the contentType twice.
  2. I've tried using EL for the value of attribute, but it doesn't get expanded.

Is there a way to dynamically set this value?

like image 900
Daniel Kaplan Avatar asked Oct 03 '22 12:10

Daniel Kaplan


1 Answers

You could try using scriptlets (not ideal, but I'm not sure there's another way), like this:

<%
    if (actionBean.isJson()) {
        response.setContentType("application/json");
    } else if (actionBean.isJsonp()) {
        response.setContentType("application/javascript");
    }
%>

Edit: And as Joop mentions in the comments, make sure you aren't setting a contentType using a @page directive.

like image 64
nerdherd Avatar answered Oct 07 '22 18:10

nerdherd