Monday 6 May 2013

Comparing Servlets and Portlets Part 2 : Using RequestDispatcher


In the last article we saw how we create a simple Servlet or a Portlet by implementing or extending appropriate interfaces and classes.

Lets continue to see what other differences are there.

RequestDispatcher

Unlike a Servlet where we can use either ServletRequest or ServletContext to get a RequestDispatcher object in a Portlet we can only use the PortletContext to do that. Just to refresh your memory RequestDispatcher can be used to forward the request to another Servlet or a JSP for further processing.



So in a Servlet I can write
-----
getServletRequest.getRequestDispatcher("/WEB-INF/jsp/hello.jsp");

or

getServletContext.getRequestDispatcher("/WEB-INF/jsp/hello.jsp");
-----

In a Portlet I can only use PortletContext to do this.

-----

getPortletContext().getRequestDispatcher("/WEB-INF/jsp/hello.jsp").include(request, response); // must start with a slash (/)
getPortletContext().getNamedDispatcher(String ServletName);

Another thing is in a Servlet we use forward primarily, although we can use include also. In a Portlet we use include if we want a JSP to process the request and display result.
You can try and play with these methods.

In the next article we will see the portlet.xml file and how it compares with the web.xml file

No comments:

Post a Comment