Using Servlets and JavaServer Pages with Portlets - Pdf 63

119
CHAPTER 5
Using Servlets and
JavaServer Pages with
Portlets
T
HE PORTLET APPLICATION
can use servlets and JavaServer Pages (JSP) in addition
to portlets. These Java 2 Enterprise Edition (J2EE) resources can be created espe-
cially for the portlet application, or they can be part of a port of an existing J2EE
application. Existing servlets and JSP will probably need to be edited to conform
to the portlet markup rules for a content fragment. In this chapter, we discuss
using servlets and JSP with a portlet. Most portlets will use JSP or another page
display technology such as Apache Velocity to render content. Rendering content
directly from a portlet is just as awkward as displaying HTML output from a servlet.
This chapter also examines using the portlet request dispatcher, which is used
to include servlets or JSP inside the portlet. The portlet passes its render request
and response objects to the servlet or JSP, and we cover the rules and exceptions
for this pass-through. In addition, we explain how to handle any exceptions the
servlet might throw inside the portlet. You’ll also learn how to deploy servlets, JSP,
and portlets together as an integrated web application.
We are not going to cover any web frameworks in this chapter. Apache Struts 2.0
and JavaServer Faces (JSF) will support portlet applications in the future. Most
popular open source frameworks will probably release a portlet module or add-on.
The biggest architectural difference is that portlets have to handle two requests
(action and render) instead of just one (like a web application).
Portlets, Servlets, and JSP Design Goals
Most portlets should use JSP or another presentation technology (like Apache
Velocity) to display their content The JSP page can share the portlet’s session,
request, and response objects easily, and there is a portlet JSP tag library to make
some tasks easy.

JSP pages into chunks of portable and nonportable code.
For exceptionally large applications (hundreds or even thousands of pages),
you may want to look into a page-generation technology with templates. Using
Apache Velocity (
/>) or another page template
language, you could define certain chunks of the templates as portlet code and
other parts as web application code. A simple generation tool that calls Velocity
could generate JSP pages for both portlets and web applications, and store them
in different folders. You could also use Velocity directly within a portlet, instead
of JSP.
Portlet Request Dispatcher
Your portlet can use a portlet request dispatcher to include the content from
a servlet or JSP page. The portlet request dispatcher translates the portlet’s render
request and render response into servlet requests and responses. Then the portlet
request dispatcher passes those servlet objects to the appropriate servlet or JSP
resource. The resource processes the render request as if the request was an
HttpServletRequest
and adds its content to the portlet’s render response. Each
portlet has access to a portlet request dispatcher through the portlet’s
PortletContext
object. The portlet request dispatcher is an object the portlet container creates
that implements the
PortletRequestDispatcher
interface. Here are the two methods
for retrieving a
PortletRequestDispatcher
object from the
PortletContext
object:
2840ch05.qxd 7/13/04 12:44 PM Page 120

There is only one method on the
PortletRequestDispatcher
object:
public void include(RenderRequest request, RenderResponse response)
throws PortletException, java.io.IOException
The
include()
method hides all of the details of loading and processing the
servlet or JSP page, just like in the servlet API.
Request Dispatcher
A portlet may use a portlet request dispatcher to include the output of either
a servlet or a JSP page. This example shows how to load a JSP page called
homePage.jsp from the WEB-INF/jsp directory of your portlet application:
PortletContext portletContext = getPortletContext();
PortletRequestDispatcher prd =➥
PortletContext.getRequestDispatcher("/jsp/homePage.jsp");
prd.include(request,response);
The
include()
method on the
PortletRequestDispatcher
object throws
a
PortletException
or an
IOException
.
You may pass a query string on the path used for the
getRequestDispatcher()
method. For instance, our previous example could look like this:

to pass a query string to a servlet or JSP that is called through a named dispatcher.
If we have a servlet named SingleSignOnServlet, we could include it when we
render the portlet, using code like the following:
PortletContext portletContext = getPortletContext();
PortletRequestDispatcher prd =➥
PortletContext.getNamedDispatcher("SingleSignOnServlet");
prd.include(request,response);
One important point is that portlets may not be included in the output of
another portlet using dispatchers. Rendering one portlet’s content inside another
portlet should be accomplished by calling methods directly to get content, providing
access to the portlet’s templates, or another form of direct access.
2840ch05.qxd 7/13/04 12:44 PM Page 122
Download at Boykma.Com
Using Servlets and JavaServer Pages with Portlets
123
Including Content in the Portlet
The content returned by a servlet should be the same type of content that the
portlet is writing out. In almost all cases, that will be character data, not binary
data. If you need to serve binary data from a portlet, provide a link directly to the
servlet from the portlet’s content. This way, your portlet application can serve
images, PDF files, and other binary data. For character data, use the
getWriter()
method on the servlet response.
Your servlet should not try to set the content type on its servlet response. The
portlet is in control of the content type, and the servlet cannot affect it. Although
your portlet sets the content type on its response, your servlet cannot get the con-
tent type from the servlet request. If your servlet works with different types of text
content (XML, HTML, etc.), you will need to manage content types with request
attributes or session parameters. You can always use two different servlet classes,
of course.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
" /><web-app>
<display-name>First Portlet</display-name>
<description>This is the first portlet.</description>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.portalbook.servlets.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
The
HelloPortlet
class is very simple. You can see how it sets up both of the
portlet request dispatchers:
Figure 5-1. Our
HelloPortlet
example showing two types of request dispatches to
a servlet
2840ch05.qxd 7/13/04 12:44 PM Page 124
Download at Boykma.Com
Using Servlets and JavaServer Pages with Portlets
125
package com.portalbook.portlets;
import java.io.IOException;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletContext;

{
2840ch05.qxd 7/13/04 12:44 PM Page 125
Download at Boykma.Com
Chapter 5
126
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.write("<BR>Hello, I'm inside a portlet.");
}
}
Our portlet.xml deployment descriptor is very ordinary because it does not
describe anything about the servlet:
<?xml version="1.0" encoding="UTF-8"?>
<portlet-app xmlns=" />version="1.0" xmlns:xsi=" />xsi:schemaLocation=" /> /><portlet>
<description>Includes a Servlet</description>
<portlet-name>HelloPortlet</portlet-name>
<display-name>Hello Portlet</display-name>
<portlet-class>com.portalbook.portlets.HelloPortlet</portlet-class>
<expiration-cache>-1</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>VIEW</portlet-mode>
</supports>
<portlet-info>
<title>Hello Portlet</title>
<short-title>Hello</short-title>
<keywords>Hello, Portlet</keywords>
</portlet-info>

getAttributeNames() Returns the names of the available attributes.
Calls getAttributeNames() on the portlet’s
PortletRequest object.
getAuthType() Returns the authentication scheme used. Calls
getAuthType() on the portlet’s PortletRequest object.
getCharacterEncoding() Returns null; does nothing.
getContentLength() Always returns 0.
getContentType() Returns null; does nothing.
getContextPath() Returns the context path associated with the portlet
application on the portal. Calls getContextPath() on
the portlet’s PortletRequest object.
getCookies() Returns cookies from properties on the portlet request.
getDateHeader() Returns a date header from properties on the
portlet request.
getHeader() Returns header from properties on the portlet request.
getHeaderNames() Returns header names from properties on the
portlet request.
getHeaders() Returns headers from properties on the portlet request.
getInputStream() Returns null; does nothing.
getIntHeader() Returns an integer header from properties on the
portlet request.
getLocale() Returns preferred locale for the portal. Calls
getLocale() on the portlet’s PortletRequest object.
getLocales() Returns locales accepted by the portal. Calls
getLocales() on the portlet’s PortletRequest object.
getMethod() Returns “GET”.
getParameter() Returns the value of the parameter from either the
portlet request, or from the query string passed into the
request dispatcher. The query string takes precedence.
2840ch05.qxd 7/13/04 12:44 PM Page 127

none. Calls getRequestedSessionId() on the portlet’s
PortletRequest object.
getRequestURI() Returns the path and query used to get the portlet’s
request dispatcher.
getRequestURL() Returns null.
getScheme() Returns the name of the URL scheme used to call the
portlet. Calls getScheme() on the portlet’s
PortletRequest object.
getServerName() Returns the server’s hostname. Calls getServerName()
on the portlet’s PortletRequest object.
2840ch05.qxd 7/13/04 12:44 PM Page 128
Download at Boykma.Com
Using Servlets and JavaServer Pages with Portlets
129
Table 5-1. The Methods on an HttpServletRequest Object in a Portlet (continued)
Method Name Method Description
getServerPort() Returns an integer representing the server’s port
number. Calls getServerPort() on the portlet’s
PortletRequest object.
getServletPath() Returns the path and query used to get the portlet’s
request dispatcher.
getSession() Same as Servlet 2.3 specification
getUserPrincipal() Returns a Principal for the current user, or null if the
user isn’t logged in yet. Calls getUserPrincipal() on
the portlet’s PortletRequest object.
isRequestedSessionId Same as Servlet 2.3 specifications.
FromCookie()
isRequestedSessionId Same as Servlet 2.3 specifications.
FromURL()
isRequestedSessionId Same as Servlet 2.3 specifications; deprecated.

Chapter 5
130
Table 5-2. The Methods on the HttpServletResponse Object
Method Name Method Description
addCookie() Does nothing.
addHeader() Does nothing.
addIntHeader() Does nothing.
containsHeader() Returns false.
encodeRedirectURL() Returns null.
encodeRedirectUrl() Returns null; deprecated.
encodeURL() Returns an encoded URL for URL rewriting for session
tracking.
encodeUrl() Returns an encoded URL for URL rewriting for session
tracking; deprecated.
flushBuffer() Flushes the buffered output to the client for the
response body, and commits the response.
getBufferSize() Returns the size of the response buffer.
getCharacterEncoding() Returns the character encoding used by the MIME
body for the portlet’s response.
getLocale() Returns the portlet response’s locale.
getOutputStream() Returns the output stream for writing binary data.
getWriter() Returns a writer for writing textual data.
isCommitted() Returns true if the response has been committed.
reset() Resets the buffer and the response properties, if the
response has not been committed.
resetBuffer() Resets the buffer if it hasn’t been committed yet. Leaves
properties alone. Useful for error message handling.
setDateHeader() Does nothing.
setHeader() Does nothing.
sendError() Does nothing.

objects. Any attributes stored on the session by a portlet are
accessible through the
HttpSession
object, and any attributes stored by servlets or
JSPs are accessible through the
PortletSession
object.
A portlet may share an object in the session for a servlet or a JSP by putting
the object into the application scope. If the object is in portlet scope, the object
will be in a namespace defined by the portlet container, and will not be easily
accessible to the servlet or JSP. The object will still be an attribute on the session,
but it would be tricky to decode the proper name. You should avoid trying to decode
an out-of-scope attribute, because it will be container-specific—this would qualify
as a hack.
Inside the portlet, you call the
setAttribute()
method on a
PortletSession
object like this:
PortletSession session = request.getPortletSession(true);
session.setAttribute("ContentManager", contentManager,➥
PortletSession.APPLICATION_SCOPE);
2840ch05.qxd 7/13/04 12:44 PM Page 131
Download at Boykma.Com
Chapter 5
132
From the JSP or servlet, you ask the
HTTPSession
object for an attribute called
ContentManager, just as you normally would do for any other object on the ses-

<taglib>
<taglib-uri> /><taglib-location>/WEB-INF/tags/portlet.tld</taglib-location>
</taglib>
2840ch05.qxd 7/13/04 12:44 PM Page 132
Download at Boykma.Com
Using Servlets and JavaServer Pages with Portlets
133
You do not need to add anything to the portlet.xml deployment descriptor to
enable the tag library, because the tags are for the JSP pages, which are processed
by the JSP compiler and servlet engine.
The <defineObjects> JSP Tag
The
<defineObjects>
tag is used to define several objects from the calling portlet’s
request in the JSP page. You can use these objects from JSP scriptlets. The tag takes
no attributes or content—it’s always used in this form:
<portlet:defineObjects/>
The variables it defines are
PortletConfig portletConfig
RenderRequest renderRequest
RenderResponse renderResponse
These objects are the same ones that are included in the request object for
a JSP or servlet in a portlet application. They can be accessed as request attrib-
utes from that request object. The
<defineObjects>
tag is a convenient shortcut
for using these objects from a JSP.
Here is an example that uses the
renderRequest
variable from the

</portlet:actionURL>
2840ch05.qxd 7/13/04 12:44 PM Page 133
Download at Boykma.Com
Chapter 5
134
The <actionURL> JSP Tag
The
<actionURL>
tag builds a URL that will send an action request to the portlet.
The action request takes parameters that are supplied by including
<param>
tags
inside the start and end pair of
<actionURL>
tags. The portlet container will process
an action request for one portlet, and then send render requests to the other portlets
on the page. For more on action requests, see Chapter 2.
Here is an example of how to use the
<param>
tag with the
<actionURL>
tag:
<portlet:actionURL>
<portlet:param name="emailID" value="13"/>
<portlet:param name="mvcAction" value="deleteEmail"/>
</portlet:actionURL>
In addition to the portlet parameters, the
<actionURL>
tag can take several
optional attributes. All of these optional attributes also apply to the

2840ch05.qxd 7/13/04 12:44 PM Page 134
Download at Boykma.Com


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status