javajspjspinclude

Return with a 500 error from inside a JSP include


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).


Solution

  • 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.