2

Is there a way to, from inside of a jsp:include page, get its requesting page to respond with an HTTP 500 error? I've tried using the response.sendError(418, "I'm a teapot.");, but that only works in the JSP that contains the jsp:include, and only if it is the first line because you can't call it after the response has been committed. What I have is this:

Index.jsp:

// other HTML

<jsp:include page="Exapmle.jsp">
    <jsp:param name="aVariable" value="aValue" />
</jsp:include>

// other HTML

Example.jsp:

<%
    String aVariable = request.getParameter("aVariable");
    if (aVariable != null && !aVariable.trim().isEmpty) {
        // code to generate content
        %><%=someContent%><%
    } else { 
        response.sendError(418, "I'm a teapot");
    }
%>

So is there any way to do this? I'm doubtful based on how JSP's work, but hoping somewhere here can help. Also, servlets aren't an option (right now, at least).

Daevin
  • 778
  • 3
  • 14
  • 31

1 Answers1

1

If you get it to work, you shouldn't rely on it to always work on all platforms and future updates. As you state correctly: Once the response has been committed (e.g. all the HTTP headers are on the way to the client) there's no more way for the server to add any other HTTP headers. Let alone change the status code.

That's the reason why JSPs are considered the VIEW layer of an application, not the CONTROLLER. The times when all application logic was written in JSPs are long over and you should have proper request handling somewhere (if only in a servlet, but probably rather in a more powerful abstraction/framework) - decide about the result and either redirect to an error message or the proper visualization in that code.

JSP is good to render the content that you send along with the proper status code. Not to decide which status code to send.

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
  • Oh, I know. I don't like needing to do this, but it's unfortunately my task right now. We're in the processes of switching to .NET MVC from Java servlets, so this is supposed to be a quick-fix to make something work before we make the switch entirely. The reasons for it are long and annoying, but such as it is my manager wants it done this way. – Daevin Mar 18 '16 at 18:49
  • Then you still should move the detection of the error condition up. If you can't promote it to the proper place, move it up to the including jsp. It's ugly and wrong, but seems to be the way to go for you. – Olaf Kock Mar 19 '16 at 09:19