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);
}
%>
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>");