tags:

views:

26

answers:

1

Hi,

I am newbie to servlets and JSP. I am trying to call logger servlet from jsp. The requirement is such that the servlet returns control to the jsp(after logging events). The servlet needs to be transparent i.e. based on the performance the logging feature may be turned off.

Is JSP:INCLUDE the only way to go? Are there other approaches?

Thanks,

Winston.

A: 

You can't call a servlet directly from a JSP. However, you can send a redirect. This will tell the browser that it should look for the resource in another location.

From JSP

<%
String destination  ="/jsp/destination.jsp";        
response.sendRedirect(response.encodeRedirectURL(destination));
%>

From Serlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException  {

String destination  ="/jsp/destination.jsp";        
response.sendRedirect(response.encodeRedirectURL(destination));

 }
}

If your purpose is "logging" you should use a Filter. A Filter is like a lightweight servlet that doesn't generate its own content, instead it plugs into the request handling process and executes in addition to the normal page processing.

A strong recommendation is to use Servlet/JSP in a MVC pattern way. It seperates the application's data, user interface and control logic into three separate entities. The request is handled by a Servlet (the controller) which will initialize any JavaBeans (the model) required to fulfill the user's request. The Servlet (the controller) will then forward the request, which contains the JavaBeans (the model), to a JSP (the view) page which contains only HTML and JSTL syntax.

Dani Cricco
-1 for "can't" and the scriptlet-approach, +1 for the Filter, this is the right way.
BalusC
:( I just wanted to point that calling a servlet from a jsp is not the right way to think. Anyway, tks for the -1+1=0 :D
Dani Cricco
One of the ways is `<jsp:include>` as already mentioned by the OP. Another (more front-controller-pattern-ish) way is to invoke first the servlet instead of JSP and then do `RequestDispatcher#forward()` to the JSP in `doGet()` method as you mentioned afterwards. But after all, the OP definitely needs a `Filter` here :)
BalusC
yep, it seems a job for a Filter
Dani Cricco