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);
}
%>
To forward a request from one page to another JSP page we can use the <jsp:forward> action. This action has a page attribute where we can specify the target page of the forward action. If we want to pass parameter to another page we can include a <jsp:param> in the forward action.
In short include, action is used to include contents of another Servlet, JSP, or HTML files, while the forward action is used to forward the current HTTP request to another Servlet or JSP for further processing.
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or another resource.
JSP forward action tag is used for forwarding a request to the another resource (It can be a JSP, static page such as html or Servlet). Request can be forwarded with or without parameter. In this tutorial we will see examples of <jsp:forward> action tag.
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>");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With