JSP pages are translated into Servlets and then compiled.
There is a difference in how the translation treats Scriptlets (% with%) and Declarations ( <% %>
).
Scritplets are translated into a service method that provides variables such as <%! %>
and request
. For example, your Scriptlet is translated into the following build in Tomcat 8 / Jasper:
public void _jspService(final HttpServletRequest request,
final HttpServletResponse response) throws IOException, ServletException {
final PageContext pageContext;
HttpSession session = null;
final ServletContext application;
final ServletConfig config;
JspWriter out = null;
final Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
// Aqui esta o seu codigo real
RequestDispatcher disp = request.getRequestDispatcher("t2.jsp");
disp.forward(request, response);
} catch (Throwable t) {
// linhas e linhas de boilerplate
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
See that you can only use response
since it was passed to the service method per parameter.
Declarations are simply copied into the Servlet body during translation, so you will not have access to request
by default. Nothing prevents you from receiving request
and request
as parameters:
<%!
public void method(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher disp = request.getRequestDispatcher("t2.jsp");
disp.forward(request, response);
};
%>
This is equivalent to declaring a method in the body of a response
.
According to the answer from Max Rogério , just declaring the method is not enough. It is necessary to invoke the method that has been declared. For this, a possible option is to write a Scriptlet that invokes the method by passing Servlet
and request
:
<%
method(request, response);
%>
This does what you want ... That said, I see little reason to do a foward this way since the JSP provides the tag response
that does the same thing:
<jsp:forward page="t2.jsp" />
In general it is better to avoid Scriptlets and Declarations , besides being a legacy technology, architecturally they are an abomination ... Mix business code with navigation rules and the view in one place creates a very difficult salad to keep.