The basic idea here is that servlets are responsible for handling requests and interacting with the business logic. The JavaServerPages are called from the servlets by forwarding or includes, with appropriate information for the JSP to deliver content (e.g. using JavaBeans).
A disadvantage of this approach: Assume an orderForm.jsp and a /servlet/orderFormController which forwards to allOrders.jsp. When the user wants to refresh allOrders.jsp by pressing "reload" on his browser, he will resubmit the orderForm.jsp results.
A workaround: Let orderFormController use a sendRedirect() instead of forward or include. -- RainerWasserfuhr
Notice that JSP's only raison d'être when used in this way is to convert html text in files to Java strings in RAM, and that it does this conversion at run-time, which means the SDK must be on the deployment server (security risk). See http://virtualschool.edu/jwaa (Java Web Application Architecture) for a way of doing the same thing at compile time, which effectively eliminates the need for JSP altogether. The approach demonstrated there separates presentation into methods instead of files to maximize compile-time typechecking, but techniques for separating them into files by integrating a template language are also described there. -- BradCox
I have used this technique a couple of times, but have ditched it in favour of servlet -> xml -> xsl. This provides a lot more flexibility and logic separation. I now fail to see the raison d'être of jsp's at all.
The raison d'être of JSP's lies in the idea of WYSIWYG. A JSP can be built all at once in a visual tool, with only a few "magical" bits representing the JSP tags. While programmers are generally comfortable with the idea of XSL and XSL transformations, it is something with which many web masters are less comfortable. If you want to make wide, sweeping changes in a site, or if you have the visual production of your site outsourced, then JSP's may be a better technology than XML/XSL. Personally, I consider them both to be valid technology choices. -- KyleBrown
Could someone please post actual code for including a JSP page from within a servlet, and passing some template variables to the JSP? It's not necessarily obvious.
Sure. In the servlet, do this:
public doGet(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("mesg", "Hello World"); getServletContext().getRequestDispatcher("message.jsp").include(request, response); }In the JSP, do this:
<%@ page %> <jsp:useBean id="mesg" scope="request" type="java.lang.String" /> <html> <head> <title>Message JSP</title> </head> <body> The message is <%=mesg%> </body> </html>