Title: Core JSP Components
1Core JSP Components Directives
2Built-in JSP Objects
- JSPs create a simplified layer on top of the
Servlet. - JSP API provides a series of built-in objects
(implicit objects) to access the information
provided by the Servlet objects of different
classes - They are created at the beginning of a page (in
the _jspService method) and directly reference
objects in the underlying servlet - However, they are only available to scriptlets
and expressions
3Built-in JSP Objects and the Corresponding
Servlet Classes
4Request Object
- request object represents the current request
from the browser - It is an instance of HttpServletRequest, a
subclass of ServletRequest interface - ServletRequest and HttpServletRequest
- Contains information about the request from the
browser such as variables and the setting of the
browser
5Request Accessing Parameters
- Request can be used to pass String values in
parameters from the client to server - String getParameter(String name)
- Retrieve a single (or first) value of the
parameter - String getParamterValues(String name)
- Retrieve multiple values of a parameter as a
String array - Enumeration getParameterNames()
- Retrieve an enumeration of all parameter names in
a request
6Request Accessing Attributes
- On the other hand, you may want to pass other
types of data (e.g. Objects). You can use an
attribute to do this. - Object getAttribute(String name)
- Similar to getParameter, retrieve the value of
the attribute - void setAttribute(String name, Object attr)
- Store a value attr to the named attribute
- void removeAttribute(String name)
- Delete the attribute and its value for the
request object - Enumeration getAttributeNames()
- Retrieve and enumeration of all attribute names
in a request
7Request Server Request Information
- String getServerName(), int getServerPort()
- Return the hostname/port number which received a
request (esp. in multi-homed server) - String getRemoteHost(), String getRemoteAddr(),
int getRemotePort() - Return the hostname/IP address/port number which
sent the request - String getProtocol()
- Return the protocol used (e.g. http/1.0)
- boolean isSecure()
- Determine whether the request is using a secured
protocol - String getMethod()
- Find out what method was used to make the request
(e.g. get/post)
8Request Request Data
- Most of the time, request contains a list of
variables. However, the request content can be
any other type of data (such as an image). - int getContentLength(), String getContentType()
- Return the length (in byte) and the content type
of the request content - -1 is returned if length is unknown, null is
returned is content type is unknown - String getCharacterEncoding()
- Return the encoding type of the content
- BufferedReader getReader(), ServletInputStream
getInputStream() - Retrieve a buffered reader (for text) / stream
(for other binary data) to read the request
content - You can only get either one of the reader and the
stream at one time. If you try use both, an
IllegalStateException occurs
9Request Request Header Values
- You sometimes need to examine header values sent
in the request - Enumeration getHeaderNames()
- Returns an enumeration of all header names
- String getHeader(String name), Enumeration
getHeaders(String name) - Gets a single value / all the values of a
particular header - int getIntHeader(String name), long
getDateHeader(String name) - Sometimes, the header contains a number or a
date. You can directly call the above method to
parse the value to the desired type. - For getDateHeader(), it returns a long int
counting the number of millisecond since 1-1-70.
You can use the value to create a new Date
instance using the Date class
10Request About Request URI
- You can separate the URL from the request to
different parts - String getRequestURI()
- Returns the URI (resource location) of the
request URL - String getContextPath()
- Returns the context path (e.g. path in the server
under the public_html director) of the request
URL - String getPathInfo(), String getPathTranslated()
- Returns any extra path information associated
with the request URL. - The extra path information follows the servlet
path but precedes the query string. - The latter method will also translate the path to
a real path - StringBuffer getRequestURL()
- Returns the whole request URL except the query
string - String getQueryString()
- Returns the list of parameters at the end of a
URL - Cookie getCookies()
- Returns an array of cookie objects passed in from
the client
11Upload Files through HTTP
- It is possible to upload a file to a JSP/Servlet
through an HTTP POST request - The difficulty is that the request content is of
the type multipart/form-data, which is usually
something like - multipart/form-data boundary--------------------
7d02d0343304ce - The actual content also starts with an additional
header - --------------------7d02d0343304ceContent-Disposi
tion form-data namefoo filenameC\temp\upl
oadFile\myUpload.txtContent-Type
application/octet-stream - The boundary is used to separate the parts in the
multiple part content - A blank line following the boundary terminates
the additional header - A boundary will also be placed after the content
12HTML File for File Upload
- lthtmlgt
- ltbody bgcolor"ffffff"gt
- lth1gtFile Uploaderlt/h1gt
- ltform action"upload.jsp" method"post" enctype
"multipart/form-data"gt - Please select a file to upload
- ltinput type"file" name"foo"gt ltpgt
- ltinput type"submit" value"Upload File!"gt
- lt/formgt
- lt/bodygt
- lt/htmlgt
13File Receiver Servlet
- package examples
- import javax.servlet.
- import javax.servlet.http.
- import java.io.
- / Receives a file uploaded via a HTTP POST
request / - public class FileReceiverServlet extends
HttpServlet - public void service(HttpServletRequest
request, HttpServletResponse response) throws
java.io.IOException, ServletException - // Get the input stream for reading the file
- InputStream in request.getInputStream()
- // The file is always saved to this file
- OutputStream fileOut new BufferedOutputStream(
new FileOutputStream("uploaded-file")) - // Create a buffer for reading bytes from
inputstream - byte buff new byte4096
- int len
- // Read bytes from the stream and write to the
file - while ((len in.read(buff)) gt 0)
- fileOut.write(buff, 0, len)
-
- fileOut.close()
14Handling Uploaded File
- In this example, we do not specify the path for
storing the file. The servlet container will
decide where it will be stored - In Tomcat, it supposed to be stored in Tomcats
bin/ folder - However, I found the file in Windows system32
folder - If you want to store the file in your Web
applications directory, you can obtain the path
using - String path getServletContext().getRealPath(/)
- For JSP, you can use implicit object application
insteadString path application.getRealPath(/
) - You may also use a JSP to receive the file
- Place the code in the service method to a
scriptlet - Remember to add an import statement usinglt_at_
page import java.io. gt - You can use the implicit object out instead of
creating a new PrintWriter
15Handling Uploaded File (contd)
- The file saved from the HTTP request still
contains the additional header - To remove the additional header, we need to add
the some codes to the JSP/Servlet - Read the content type to extract the boundary
format and find out its length - Skip the first lines (additional header) from the
content until a blank link is read - Write the rest of the content into a file except
skipping the last few bytes that represents the
ending boundary - In the following example, we have used a
ByteArrayOutputStream to simplify the task of
extracting the ending boundary - You can also extract the file name from the
additional header using the methods in String
16File Upload Handler (JSP) (1)
- lt_at_ page import "java.io." gt
- lt // Get the content type
- String contentType request.getContentType()
- // Find out where the boundary string starts
- int boundaryIndex contentType.indexOf("boundary
") - // Get the boundary string
- String boundary contentType.substring(boundaryI
ndex9) - // Set a default for the boundary string length
- int boundaryStrLength boundary.length()
- // Get the input stream to read the uploaded
file - ServletInputStream servIn request.getInputStrea
m() - DataInputStream in new DataInputStream(servIn)
- // Lop off the headers from the content
- //(read until you get a blank line)
- String line
- while ((line in.readLine()) ! null)
- application.log("Got line "line)
- if (line.trim().length() 0) break
-
17File Upload Handler (JSP) (2)
- // Create a ByteArrayOutputStream to store the
bytes read - ByteArrayOutputStream byteOut new
ByteArrayOutputStream( request.getContentLength
()) - byte buffer new byte4096
- int len
- // Copy the uploaded file to a byte array
- while ((len in.read(buffer)) gt 0)
- byteOut.write(buffer, 0, len)
-
- byte outBytes byteOut.toByteArray()
- FileOutputStream fileOut new FileOutputStream(
- application.getRealPath("/") "/upload")
- // Write the byteArray to the file, trim the
closing boundary - fileOut.write(outBytes,0,outBytes.length-boundary
StrLength-8) - fileOut.close()
- // Tell the Web server that the response is HTML
- response.setContentType("text/html")
- // Write the HTML back to the browser
- out.println("lthtmlgtltbodygt")
- out.println("File Accepted, thank you.")
18Response Object
- When a JSP needs to send data back to the
browser, it uses the built-in response object - You can also set the content type, length, and
character encoding of the file - void setContentType(String contentType)
- void setContentLength(int contentLength)
- ServletOutputStream getOutputStream()
- Return a servlet output stream for outputing data
other than characters - PrintWriter getWriter()
- You can use the built-in object out and send
the output directly - String getCharacterEncoding()
19Response Buffer
- Usually, the JSP response is buffered. There are
methods for you to control the buffer as you want - int getBufferSize(), void setBufferSize(int
bufferSize)get/set the buffer size you cannot
change the buffer size once you have written
something out - void flushBuffer()send the current buffer
contents to the browser immediately - void reset()clear the buffer contents
- boolean isCommitted()Once you have send the
response status to the borwser, the response is
committed and you cannot modify the header
value. This method is to check if the response
object is committed
20Response Header
- Most header variables can be set through the
response object using corresponding methods - You can set the headers directly if the
corresponding methods are not found - void setHeader(String header, String value)
- void setIntHeader(String header, int value)
- void setDateHeader(String header, Date value)
- For multiple header values, you use the add
methods instead of the set methods - void addHeader(String header, String value)
- void addIntHeader(String header, int value)
- void addDateHeader(String header, Date value)
- You can also check if a header value is already
existed - Boolean containsHeader(String header)
21Response Other Methods
- Redirection void sendRedirect(String URL)
- A forward action (will be taught later) is more
efficient than using a redirection - Return Status
- void setStatus(int statusCode)
- void setError(int statusCode)
- void setError(int statusCode, String
errorMessage) - URL Encoding
- When you want to send a URL to the browser, you
need to call encodeURL/encodeRedirectURL. - The methods will append a session ID parameter to
the URL if the browser does not support cookies - String encodeURL(String url)
- String encodeRedirectURL (String url)
- Sending Cookies
- void addCookie(Cookie cookie) will be discussed
later in this chapter
22JSP I/O Streams out Object
- ServletInputStream and ServletOutputStream is
normally used to handle binary data other than
text - ServletInputStream extends InputStream with a
readLine method added - ServletOutputStreasm extends OutputStream with
all print and println methods as in PrintStream
class - out is a JspWriter object acts like a PrintWriter
- out supports almost all print, println and write
(for char arrays with offset and length) methods - You can control the buffer of JspWriter, but you
are advised to use the default setting
23Session Object
- session object stores information between browser
requests. You can also control the session expiry
time through the session object - Methods for storing and retrieving session
information - Object getAttribute(String name)
- void setAttribute(String name, Object value)
- void removeAttribute(String name)
- Enumeration getAttributeNames() this return an
enumeration containing all attributes stored in
the session - Methods controlling session termination
- void invalidate() useful for invalidating the
users session when the user logs out - void setMaxInactiveInterval(int interval) / int
getMaxInactiveInterval() change/retrieve the
session timeout (in minutes)
24Session Status
- Each session object has an unique identifier
(unique in your servlet engine) - String getId()
- boolean isNew() check if a session is just
created - long getCreationTime()
- long getLastAccessedTime()
- Access time is counted only if the access is from
the request (browser)
25pageContext Object
- A central repository for information that a JSP
might need to obtain - Create at the beginning of the servlet for the
JSP and destroy at the end of it - Use to intialize / retrieve the objects for the
built-in variables - Capable to scan for attributes and attribute
names among all scope (page, request, session and
application) - Facilitate forward and include of servlet or JSP
26pageContext Accessing Own Attributes
- An attribute stored in pageContext has a scope of
page only - JavaBeans with a page scope are also stored as
attributes in pageContext - Methods for storing, retrieving and removing
attributes in pageContext - Object getAttribute(String name)
- void setAttribute(String name, Object o)
- void removeAttribute(String name)
27pageContext Accessing Attributes of Other Scopes
- Accessing attributes in any other scope
- Object getAttribute(String name, int scope)
- void setAttribute(String name, Object o, int
scope) - void removeAttribute(String name, int scope)
- Scope are defined by constants PAGE_SCOPE,
REQUEST_SCOPE, SESSION_SCOPE and
APPLICATION_SCOPE in pageContext. - Enumeration getAttributeNamesInScope(int scope)
retrieves all attribute names in the given scope - Object findAttribute(String name) searches for
an attribute value through all scopes
28Forwarding and Including
- Normally we use action tags (will be taught
later) ltjspincludegt and ltjspforwardgt to do the
tasks - If forward and include services are needed inside
a scriptlet, you can call the following methods
from pageContext - void forward (String url)
- void include (String url)
- void include (String url, boolean flush) you
can prevent the buffer being flushed prior to the
include statement by setting flush to false
29Cookie
- A cookie is a value stored on the browser
- The value is sent to the server whenever the
browser requests a page - Data such as username and session ID are usually
stored in the browser and sent as a cookie - Not all cookies are sent to a server. Only the
cookies that match the server's domain and path
will be sent - Constructor Cookie(String name, String value)
- String getName(), String getValue() returns the
name and value of a cookie - void setValue(String newValue) changes the cookie
value - String getDomain(), void setDomain(newDomain)
gets/sets the domain of the cookie - String getPath(), void setPath(String newPath)
gets/sets the server path of the cookie - int getMaxAge(), void setMaxAge(int maxAge)
gets/sets the expire time for a cookie (in
seconds)
30Other JSP Objects
- config object
- gives you access to configuration information for
your JSP - page object
- a reference to the current JSP, seldom used
- exception object
- gives you access to the exception that caused the
error page
31JSP Directives
- lt_at_ gt is a directive tag. There are three
directives in JSP specification - page directives for different page options
- include directives enables you to include other
files at compile time - taglib directives enables you to include an
external custom JSP tag library
32Page Directive
- Setting page option in the form of namevalue,
e.g. lt_at_ page info"First JSP" gt - You cannot have two page directives with the same
option in the same page except import and
pageEncoding option - Common page directives
- contentType specifies the kind of data that is
returned. Default type is text/html. Can also be
combined with the character encoding for the
response. Example lt_at_ page contentType"text/htm
lcharsetISO-8859-1" gt - pageEncoding specifies the character encoding
used in the JSP. Default value is ISO-8859-1
(Latin 1)
33Page Directive (cont'd)
- language default is java, which is the only
language in the current specification - import imports the necessary packages. Can be
used to import multiple packageslt_at_ page
import"java.sql.,java.util.,java.math." gt - info provides a description of the servlet
- session denotes if session is used, default is
true - buffer control the JSP buffer. Turn off buffer
by setting the buffer option to "none"E.g.,
lt_at_page buffer"16" gt sets buffer to 16 KBOnly
the minimum size is set. A larger size may be
used by the JSP engine
34Page Directive (cont'd)
- autoFlush automatically flushes the buffer when
it fills. Default value is true. If set false,
JSP Engine will throw an exception - errorPage denotes the page used to display
error during the current page is runlt_at_ page
errorPage"handleError.jsp" gt - isErrorPage indicates if the current JSP is
used as the error Page of another JSP - extends enables you to specify the superclass
for your JSP. Usually HttpServlet class is
extended Two methods must be added to the
superclass jspInit() and jspDestory().In your
service method, you must invoke _jspService
method in the JSP
35isThreadSafe Option in Page Directive
- By default, all JSPs are considered thread-safe
- i.e., the servlet container allows multiple
threads to use the same JSP instance at the same
time. - You may set this option to false to acknowledge
the servlet container that your page can be
accessed by one thread at one time - However, the checking method has been deprecated
in Servlet 2.4 (current) specification - You should in fact try to guarantee your JSPs are
thread-safe
36Example on Error Page Related Options
- This is the JSP error page handling the error
- lt_at_ page isErrorPage"true" gt
- lthtmlgt ltbodygt
- lth1gtErrorlt/h1gt
- An error occurred while processing your request.
ltpgt - The error message is lt exception.getMessage()
gt. - lt/bodygt lt/htmlgt
- This is a page that generate an exception
- lt_at_ page errorPage "ErrorPage.jsp" gt
- lthtmlgt ltbodygt
- You shouldn't see this because an exception will
be thrown soon. - lt if (true) throw new RuntimeException(
"You've got an error!") - gt
- lt/bodygt
- lt/htmlgt
37Example on JSP superclass
- import javax.servlet.
- import javax.servlet.http.
- import javax.servlet.jsp.
- public abstract class JSPSuperclass extends
HttpServlet - implements HttpJspPage
- // methods must be declared final
- // for the class is a superclass for JSP
- public final void init(ServletConfig c) throws
ServletException - super.init(config) // Superclass do its
initialization - jspInit() // Initialize the JSP
-
- public final void destroy()
- super.destroy()
- jspDestroy()
-
- public final ServletConfig getServletConfig()
- return super.getServletConfig()
-
- public final void service(ServletRequest req,
ServletResponse res) throws ServletException,
java.io.IOException
38Example on JSP superclass (cont'd)
- public final void service(HttpServletRequest
req, HttpServletResponse res) throws
ServletException, java.io.IOException - // DEMO ALERT! Put a dummy data item in here to
show - // how the subclassing works
- request.setAttribute("Demo", "Hello from your
superclass") - // Now call the _jspService method to run the
JSP - _jspService(request, response)
-
- // Provide a dummy jspInit method
- public void jspInit()
- // Provide a dummy jspDestroy method
- public void jspDestroy()
- // The _jspService method is implemented by
- // the servlet generated from the JSP page
source - public abstract void _jspService(HttpServletReque
st request, HttpServletResponse
response) throws ServletException,
java.io.IOException -
39Include Directive
- Using include tag can make your JSPs more
readable - To include another file at compile time, we use
the include directive - lt_at_ include file"include_file" flush"true" gt
- flush option will indicate the output buffer to
flush before the file is included - You can use an identical file for the common
feature in all pages in your application. - When you want to change the common feature, you
need to change one file (the one that stores that
common feature) only - Only Tomcat will detect if your included file has
been changed. Other servlet container does not
guarantee the checking
40JSP Standard Action
- JSP action tags ltjspXXX /gt cause programmatic
behavior to occur - These actions are also known as JSP standard
action
41Including Files in Runtime
- If you want to include a servlet/JSP during
runtime, you can use include action tag - ltjspinclude page"include_file" flush"true" /gt
- flush attribute indicates whether the output
buffer should be flushed before the file is
included. Default value is false - Passing parameters to an included file
- ltjspinclude page"somePage" flush"true"gt ltjspp
aram name"parameter" value"value"
/gtlt/jspincludegt - Note that the closing tag can be in a line
different from opening tag - Only the including page can use the parameter
42Including JSP into a Servlet
- In servlet, we need to obtain a request
dispatcher to include a JSP/text file and pass
the current request and response to the the
dispatcher - RequestDispatcher d request.getRequestDispatche
r("destinationURL")d.include(request,
response) - The output from the included resource is written
to the stream of the response object - The parameter needed by the JSP should be
attached to the URL as a query string
43Example of Include Directive
- The main page
- lthtmlgt
- ltbodygt
- lt_at_ include file"Header.html" gt
- ltpgt
- Welcome to ltigtIt's a Crazy Worldlt/igt
- ltpgt
- lt/bodygt
- lt/htmlgt
- The included header
- lttable bgcolor"0000ff"gt
- lttrgtlttdgtltimg src"face.jpg" alignleftgt
- lttdgtlth1gtltfont color"ffff00"gtIt's a Crazy
World lt/fontgtlt/h1gt - lttdgtltimg src"face.jpg" alignrightgt
- lt/tablegt
44Example of Including JSP at Runtime
- Support.jsp, with Menu.jspf shown in next page
- lthtmlgt ltbody bgcolor"ffffff"gt
- lt_at_ include file"Header2.html"gt
- ltjspinclude page"Menu.jspf" flush"true"gt
- ltjspparam name"highlighted"
value"aboutUs"/gt - lt/jspincludegt
- ltpgt
- We are just humble zither players who want to
let the world know about these wonderful
instruments. Plus, the amalgamatedzithers.com
domain was still available. - lt/bodygt lt/htmlgt
45Example of Including JSP at Runtime
- lt // See which menu item should be highlighted
- String hl request.getParameter("highlighted")
- // Set the names for the individual menu items
- String welcome "welcome.jpg"
- if (hl.equalsIgnoreCase("welcome")) welcome
"welcomeS.jpg" - String products "products.jpg"
- if (hl.equalsIgnoreCase("products")) products
"productsS.jpg" - String services "services.jpg"
- if (hl.equalsIgnoreCase("services")) services
"servicesS.jpg" - String support "support.jpg"
- if (hl.equalsIgnoreCase("support")) support
"supportS.jpg" - String aboutUs "aboutUs.jpg"
- if (hl.equalsIgnoreCase("aboutUs")) aboutUs
"aboutUsS.jpg" - gt
- lttable cellpadding"0" cellspacing"0"gt lttrgt
- lttdgtlta href"welcome.jsp"gtltimg src"ltwelcomegt"
border"0"gtlt/agt - lttdgtlta href"products.jsp"gtltimg
src"ltproductsgt" border"0"gtlt/agt - lttdgtlta href"services.jsp"gtltimg
src"ltservicesgt" border"0"gtlt/agt - lttdgtlta href"support.jsp"gtltimg src"ltsupportgt"
border"0"gtlt/agt
46Example of Passing Parameters to an Included JSP
- MainForm.jsp
- lthtmlgt
- ltbody bgcolor"ffffff"gt
- ltjspinclude page"IncludedForm.jspf"
flush"true"gt - ltjspparam name"myVar" value"Passed from main"
/gt - lt/jspincludegt
- lt/bodygt
- lt/htmlgt
- IncludedForm.jspf
- ltpregt
- lt String myVar request.getParameter("myVar")
- String myVars request.getParameterValues("my
Var") - out.println("myVar"myVar)out.println("The
values of myVar are") - for (int i0 i lt myVars.length i)
- out.println(myVarsi)
-
- gt
- lt/pregt
47Forwarding Using forward Action Tag
- JSP action tag for forwarding is very similar to
the including syntax - ltjspforward page"destination" /gt
- Your original page is replaced with the new page
even any output you might have to sent to the
buffer will be cleared - You may get an IllegalStateException when you
forward a page this may be because your buffer
has been flushed to the client before the file is
forwarded - You can also pass your parameters to a forward
page using ltjspparamgt tag
48Forwarding from a Servlet
- Similar to including a file into a servlet,
forward to a JSP can be done in a servlet using a
request dispatcher - RequestDispatcher d request.getRequestDispatche
r("destURL")d.forward(request, response) - Similarly, you can pass your parameters through a
query string appended to the destination URL
49Example of JSP Forwading
- lthtmlgt
- ltbodygt
- You should never see me because my output is
erased before forwarding. - ltjspforward page"ForwardedPage.jsp"/gt
- lt/bodygt
- lt/htmlgt
50Example of Forwarding from a Servlet
- import javax.servlet.
- import java.io.
- public class ForwarderServlet extends
GenericServlet - public void service(ServletRequest req,
ServletResponse resp) throws IOException,
ServletException - // Tell the web server that the response is HTML
- response.setContentType("text/html")
- // Get the PrintWriter for writing out the
response - PrintWriter out response.getWriter()
- // Write the HTML back to the browser
- out.println("lthtmlgt ltbodygt")
- out.println("You should never see this")
- out.println("because my output buffer gets
erased") - // Get the request dispatcher for the JSP to
include - RequestDispatcher dispatcher
- request.getRequestDispatcher("/ForwardedPage.jsp
") - dispatcher.forward(request, response)
- out.println("lt/bodygt lt/htmlgt")
-