Question

Is there a pure-Java equivalent to <jsp:forward page="..." /> that I can use within a <% ... %> block?

For example, I currently have a JSP page something like this:

<%
    String errorMessage = SomeClass.getInstance().doSomething();
    if (errorMessage != null) {
        session.setAttribute("error", errorMessage);
%>
<jsp:forward page="error.jsp" />
<%
    } else {
        String url = response.encodeRedirectURL("index.jsp");
        response.sendRedirect(url);
    }
%>

Having to break the <% ... %> block to use the jsp:forward is ugly and makes it harder to read due to indentation, among other things.

So, can I do the forward in the Java code without use the JSP tag?

Something like this would be ideal:

<%
    String errorMessage = SomeClass.getInstance().doSomething();
    if (errorMessage != null) {
        session.setAttribute("error", errorMessage);
        someObject.forward("error.jsp");
    } else {
        String url = response.encodeRedirectURL("index.jsp");
        response.sendRedirect(url);
    }
%>
Was it helpful?

Solution

The someObject you are looking for is pageContext.

This object is implicitly defined in JSP, so you can use it like this:

pageContext.forward("<some relative jsp>");

OTHER TIPS

You really should try and avoid scriplets if you can, and in your case, a lot of what you are doing can be replaced with JSTL code. The following replacement for your example is much cleaner, IMO:

<%
  // Consider moving to a servlet or controller/action class
  String errorMessage = SomeClass.getInstance().doSomething();
  pageContext.setAttribute("errorMessage", errorMessage);
%>
<c:choose>
  <c:when test="${not empty errorMessage}">
    <c:set var="error" scope="session" value="${errorMessage}" />
    <jsp:forward page="error.jsp" />
  </c:when>
  <c:otherwise>
    <c:redirect url="index.jsp" />
  </c:otherwise>
</c:choose>

Ideally, you'd modify error.jsp so that the error message doesn't even need to be set in the session, but I didn't want to change your design too much.

A simple approach:

<%@page errorPage="Error.jsp" %>

<%
 String errorMessage = SomeClass.getInstance().doSomething();
 if (errorMessage != null) {
       throw new Exception(errorMessage); // Better throw the exception from doSomething()
 }
 pageContext.forward("index.jsp");
%>


Error.jsp
.........
<%@ page isErrorPage='true' %>
<%
out.print("Error!!!");  
out.print(exception.getMessage());
%>

Better approach:

Invoke the doSomething() from a servlet. Set your error page in web.xml

<error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/WEB-INF/jsp/Error.jsp</location>
</error-page>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top