servlets, jsps and reflection. tonight we will discuss u mvc u other dynamic web page generation...
TRANSCRIPT
Servlets, JSPs and Reflection
Tonight we will discuss
MVC
Other Dynamic Web Page Generation Technologies
HTTP
Request
Response
Servlets
Session Tracking
Servlets and Threads
JSP
Dynamic Programming using Reflection
MVC – Model, View, Controller
Separate layers increase reuse Components are “Plug and Play” Model
Representation of the data layer Business Logic, beans, etc.
View User Interface - what to show & how to show it
Controller The core functionality of the system Handles data, responds to requests All interactions with the system are through the Controller
Multi-Tiered Web Application Development
Application Server
Application Server
ServletServlet
DataSource
DataSource
InternetInternetWeb ServerWeb Server
JVM
JSPsJSPs
HTTP
Controller
View
HTML,CSV,XML
Model
Business Logic,Beans
JDBC
Firewall Firewall
Dynamic Web Page Generation Technologies
Microsoft ASP
Netscape Server-Side JavaScript
CGI
Java Servlets and Java Server Pages
Microsoft ASP
Runs on: Microsoft IIS servers Windows NT Windows 2000
Requires knowledge of one of the following: Visual Basic JScript VBScript Active X Microsoft Managed Extensions for C++ C#
Not OS independent May have browser compatibility issues with Netscape Communicator
Netscape’s Server Side Javascript
Runs on: Windows NT Windows 2000 LINUX and Unix Platforms
Need Netscape / iPlanet Enterprise or FastTrack web servers Requires knowledge of:
Server-Side Javascript Client Side JavaScript
May have browser compatibility issues with Internet Explorer Needs to interface with Java for more complex applications
Common Gateway Interface
Requires knowledge of one of the following: Perl PHP C++
Can be implemented on most web servers with a server specific API Runs on:
Windows NT Windows 2000 LINUX and Unix platforms
Requires a new operating system process for each CGI request A CGI program terminates after each request. Persistent data storage is
difficult to maintain
Java Servlets and JSP
Platform independent. Write once, run anywhere… Many open source servlet engines that integrate with most
popular web servers (Apache, IIS, NES / Windows98/NT, Solaris, Linux)
Combines with the rest of Java API to form an integrated application solution Ability to leverage all the advantages of the Java
language, as well as any API’s available to Java (JDBC, RMI, CORBA, JNDI)
Each HTTP request creates a new thread, as opposed to a new OS process (faster than CGI scripts)
Built in support for session tracking and persistent data
Java and the Open Systems Interconnection (OSI) Model
Physical
Data
Network
Transport
Session
Presentation
Application
Phyical MediaCoax Cable
Fiber Optic CableEtc.
Address Resolution ProtocolInternet Protocol (IP)
Internet Control Message Protocol
EthenetToken Ring
FDDl
Transport Contol ProtocolUse DatagramProtocol
Simple Mail Transfer Protocol (SMTP)File Transfer Protocol (FTP)
Hyper Text Transport Protocol (HTTP)
W eb BrowsersE-mail ClientsFTP Clients
javax.mailjava.io.file with java.net
javax.servlet
java.net.Socketjava.net.ServerSocket
java.net.DatagramPacketjava.net.DatagramSocket
javax.swingjava.awt
java.net.InetAddressjava.net.URL
OS Specific Drivers
Hardware
What is a servlet? (1)
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model.
- java.sun.com
What is a servlet? (2)
A module that extends request-response servers
An application that runs on the server
This is much different from an applet, which runs on the client side, and needs a web browser
It can perform any number of tasks, including interfacing with a database.
Servlet Request Response
Servlet
Request
Response
Server
Why use servlets? (1)
Portability
Write once, serve everywhere
Power
Can take advantage of all core Java APIs
Elegance
Simplicity due to abstraction
Efficiency & Endurance
Instance persistence, highly scalable
Why use servlets? (2)
Integration
Servlets tightly coupled with server
Can utilize the computing power of the server
Extensibility & Flexibility
Servlets designed to be easily extensible, though currently optimized for HTTP
Flexible invocation of servlet (SSI, servlet-chaining)
Safety
Strong type-checking
Memory management
HTTP and the Java Servlet API
The Java Servlet API is designed to provide an HTTP interface for application development
HTTP is based on a request - response paradigm
The HTTP client sends a request to an HTTP server
The HTTP server sends a response to an HTTP client
HTTP requests and responses are stateless
ClientServer
HTTP Response
HTTP Request
HTTP Request (1)
GET method for getting information from server can include query string, sequence with additional
information for GET, appended to URL• (+) query string can be bookmarked• (-) some servers limit this string to 240
characters POST method
designed to give information to server all information (unlimited length) passed as part of request
body• (+) invisible to user• (+/-) cannot be reloaded or bookmarked (by
design)
HTTP Request (2)
PUT method
A request to send a file via FTP Delete method
A request to delete a URI from the server Trace method
A request to send all the headers sent with the trace request
Options
Used to implement new request not currently supported in HTTP 1.1
Handling Requests in a Servlet
In Java, everything is an object
A Servlet is an object
There are methods corresponding to each of the different request types
doGet()
doPost()
doPut()
doDelete()
doTrace()
doOptions()
HTTP request headers (1)
There are a number of headers that come with an HTTP request, which contain information about the type of browser, the length of the request (for a put request), cookie information, etc.
HTTP request headers (2)
Accept specifies the MIME types a browser can handle
• text/html, image/jpeg, application/pdf, etc. Accept-Charset
specifies the character sets a browser can handle. Accept-Encoding
specifies if the browser supports encoding formats such as gzip or compress. Accept-Language
specifies the clients preferred language based on RFC 1766. Authorization
used by clients to identify themselves to password protected web pages Cache-Control
specifies how pages should be cache by proxy servers Connection
tells the server if the client can handle persistent connections Content-Length
Gives the size of the post data in bytes Content-Type
used by the client when a document is attached or when making PUT request. Cookie
returns the cookie to the server that originally sent it.
HTTP request headers (3)
Expect allows the client to tell the server what kind of behavior it expects usually in the form of
a status code From
identifies to the server the e-mail address of the client responsible for the request. Browsers do not send this header but wide spiders do.
Host a required header for HTTP 1.1 that indicates the host address and port given in the
original URL of the web page sent by a server. If a server is using request forwarding or supporting multiple hosts, the server may not
be able to otherwise determine this information User-Agent
identifies the browser or client software making the request. If-Modified-Since
indicates that the client wants the specified page only if it has been changed after a specified date.
If-Unmodified-Since indicates the should succeed only if the document is older than the specified date. It is
used for PUT request.
HTTP request headers (4)
If-Match The client supplies a list of entity tags as returned by the ETag response header. An operation is performed
only if one of them matches. Used primarily with PUT request If-None-Match
similar to If-Match header, performs an operation if no entity tags match. Referrer
indicates the URL of the referring web page. Upgrade
indicates the client prefers another communication protocol over HTTP 1.1. Pragma
indicates that a servlet that is acting as a proxy should forward the request even it has a local copy If-Range
lets a client that has a partial copy document ask for the missing parts or an entirely new copy of the document.
Range allows the client that has a partial copy of a document ask for only the parts it is missing.
Proxy-Authorization lets client identify themselves to proxies that require it.
Example HTTP request header
Get / index.html HTTP/1.1
Accept: text/html
Accept: image/gif
Accept: image/jpeg
Accept: application/pdf
User-Agent: Lynx/2.4 libwww/2.1.4
What happens when a request arrives
HTTP request
ServletEngine
HttpServletRequest
HttpServletResponse
HttpServlet
HttpServletRequest
Represents an HTTP request.
Data from the client is supplied to the servlet for use in
doGet(),
doPost(),
doPut(),
doDelete(), etc.
or service() method in the HttpServlet class.
Provides wrapper methods to retrieve all of the information available in an HTTP request
HttpServletRequest API (1)
public String getAuthType() Returns the HTTP authentication scheme of the request. Return null if no authentication is present. Returns “ASCII” for text authentication and “SSL” for secure sockets layer.
public Cookie[] getCookies() Returns all of the Cookie objects found in this request as an array.
public long getDateHeader(String name) This returns the value of the given date header or -1 if the field is not known. The string variable used as an input parameter is not case sensitive. Throws an IllegalArgument exception if the header cannot be converted into a
date. public String getHeader(String name)
Returns the value of the given header field or null it the header field is not known. The name header field is not case sensitive.
HttpServletRequest API (2)
public int getIntHeader(String name) Returns the integer value of the given header field or -1 if the header field value is
not known. The name of the header field is not case sensitive.
public Enumeration getHeaders(String name) Returns a enumeration of header values for a given header name. It returns null if the header values cannot be accessed by the server. For example the Accept-Language header can be sent by clients as several
headers each with a different value rather than sending the header as a comma separated list.
public Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains. If the request has no headers returns an empty enumeration.
public String getMethod() Returns the method used by the client to make the request. The returned value can be “GET”, “HEAD”, or “POST”.
HttpServletRequest API (3)
public String getPathInfo() Returns optional extra path information following the servlet path associated with
the URL sent by the client. Returns null if no path information is present.
public String getPathTranslated() Returns extra path information, which is translated into a physical path. Returns null if on path information is present.
public String getContextPath() Returns to portion of the URI request that identifies the context of the request. The path starts with a “/” character but does not end with a “/” character. For servlet in the default or root context returns “”.
public String getQueryString() Returns the query string portion of the servlet URI. The information is usually in the form of n1=value&n2=value&n3=value. Returns null if no query string is present.
HttpServletRequest API (4)
public getRequestedSessionID() Returns the session ID specified by the client.
public String getRequestURI() Returns the portion of the URL from the protocol name up to the query
string in an first line of an HTTP request. public String getServletPath()
Returns the path of the request’s URL that calls the servlet. public HttpSession getSession()
Returns the current instance of an HttpSession object if one a instantiated.
If the request does not have an HttpSesion one is created. public HttpSession getSession(boolean create)
Returns the current instance of an HttpSession object if one a instantiated.
If the request does not have an HttpSesion and create is true one is created.
HttpServletRequest API (5)
public boolean isRequestedSessionIDValid() Returns true if this request is associated with a session that is valid in
the current context. public boolean isRequestSessionIDFromCookie()
Returns true if the requested session ID came from a cookie. public boolean isRequestSessionIDFromURL()
Returns true if the requested session ID came from as part of the URL. public java.Security.Principal getUserPrinciple()
Returns a java.Security.Principal object containing the name of the current authenticated user.
public String getRemoteUser() Returns the login name of the user making the servlet request, if the
user has been authenticated. Return null otherwise.
HttpServlet request handling
GET request
service()service()
HttpServlet
responsedoGet()doGet()
doPost()doPost()
Web Server
POST request
response
Servlet Engine
HTTP response
Three parts to a response
Status code (404 “Not Found”, 200 “OK”)• public void HttpServletResponse.setStatus(int sc)• public void HttpServletResponse.setStatus(int sc, String sm)
HTTP headers (i.e. content-type)
Response body
HTTP Status Codes
Status Codes are used to indicate normal status or indicate any errors that may have occurred which prevent the request from being filled.
100 – 199• indicates the client should respond with some other action.
200 – 299• indicates the request was created.
300 – 399• indicates a file has moved. A location header is usually
included indicating the new address.
400 – 499• indicates an error by the client.
500 – 599• indicates an error by the server.
HTTP Response Headers (1)
Connection indicates whether the server accepts persistent HTTP connections. Requires a Content-Length response header.
Content-Encoding indicates the method used to encode the page for transmission.
Content-Language specifies the language the document was written in, based on RFC 1766.
Content-Length indicates the number of bytes for the response.
Content-Location supplies an alternative address. This header is informational. Responses that include this header also include the requested document.
HTTP Response Headers (2)
Age used by proxies servers to indicate how long ago the document was generated by the original server. New for HTTP 1.1.
Accept-Ranges indicates to the client whether the server accepts Range request headers
Allow specifies the HTTP request (GET, POST etc.) types that the server is configured to support.
Cache-Control indicates to the client the conditions required to safely cache a document.
Content-MD5 Provides an MD-5 digest for the subsequent document. This digest provides a message integrity check for clients that want to confirm the requested document is
complete and unaltered. Content-Range
This header is sent with partial document responses. It specifies how much, in bytes, of the total document was sent.
Date specifies the current date in GMT format. Most servers set this header automatically.
HTTP Response Headers (3)
Last-Modified indicates to the client when the document was last changed.
Location notifies the document of the document’s address. The browser automatically reconnects to this address and retrieves the new document.
Expires stipulates the time which the content should be considered out of date and no longer be
cached. ETag
a new header for HTTP 1.1 gives names to returned documents so that they can be reference by the client later using
the If-Match, and If-None-Match request headers. Refresh
indicates how soon in seconds the browser should ask for an updated page. Retry-After
often used with status code 503 Service Unavailable to tell the client how soon it can repeat its request.
Server identifies the web server. Usually set by the web server itself.
Example HTTP Response Header
Get / index.html
HTTP/1.1 200 OKDate: Tue, 24 Apr 2001 12:00:20 GMTServer: Apache 1.3.9Content-Type: text/htmlContent-Type: image/jpegContent-Type: image/gifContent-Length: 5492Content-Language: enCache-Control: publicConnection: close
HTTP Response body
Sequence of bytes (HTML, image) Any length Status code and headers must be sent before the response
body HTML can be generated by hand Can use HTML generation packages to abstract away the
details of HTML Images can be sent by using an appropriate encoder
HttpServletResponse
Represents an HTTP response.
Allows a servlet to return HTTP specific header information and data back to the requesting client
Has appropriate methods for setting header information and status.
HttpServletResponse API (1)
public void addCookie(Cookie cookie) Adds the given cookie to the response.
public void addDateHeader(String name, long date) Adds a response header with the given name and the given date
value. public void addHeader(String name, String value)
Adds a response header with the given name and string value. public void addIntHeader(String name, int value)
Adds a response header with the given name and integer value. public boolean containsHeader(String name)
Returns true if the response header has been set, otherwise it is false. public void setDateHeader(String name, long date)
Sets a date header with a specified name and date value. public void setHeader(String name, String value)
Sets a response header with a specified name and string value.
HttpServletResponse API (2)
public void setIntHeader(String name, int value) Sets a response header with a specified name and integer value.
public void setStatus(int statuscode) Sets the HTTP status code for the response. Encodes the give URL for use in the sendRedirect method. Returns the url string unchanged if encoding is not required.
public String encodeURL(String url) Encodes the given URL by including the sessionID in it. If encoding is not required returns the url value as a string.
public void sendError(int errorcode) Sends an error response with the specified HTTP error code.
public void sendError(int errorcode, String message) Sends an error response with the specifice HTTP error code and descriptive
message. public void sendRedirect(String location)
Sends a temporary redirect response to the client with a temporary location URL.
So… what now?
We just looked at 2 different classes that are available for use by a servlet.
How do you create a servlet?
All servlets must implement the Servlet interface.
The Servlet Interface
Interface that all servlets must implement
Contains the following methods:
void init(ServletConfig config)
• Called upon instantiation void service(ServletRequest req, ServletResponse res)
• Called whenever there is a client request void destroy()
• Called when the servlet is destroyed (free resources)
String getServletInfo()
• Returns version and copyright information
The GenericServlet class
Is abstract
Provides simple implementations of the init() and destroy() methods, and all of the methods of the ServletConfig interface.
If a class is a subclass of the GenericServlet class, it must override the service() method to provide the desired servlet functionality.
ServletServletServletConfigServletConfig
GenericServletGenericServlet
GenericServlet API (1)
protected GenericServlet() The default constructor for the GenericServlet class. The constructor does no work.
public void init(ServletConfig config) throws ServletException This method is called when the servlet is first loaded by a service. This method should be call to perform servlet initialization such as database
connections, a file loading, etc. It is guaranteed to complete before any service requests are accepted by the
servlet. If a fatal error occurs during initialization, an UnavailableException should be
thrown. The init method stores a ServletConfig object that is passed. If this method is override by the servlet developer, super.init() must be called.
service(ServletRequest, ServletResponse) handles a single request from a client. The ServletRequest object contain parameters provided by the client. It also contains an input stream which can be used to retrieve data. The servlet can return data to the client by writing to an output stream.
GenericServlet API (2)
public String getInitParameter(String name) Returns a string value for the name initialization parameter. Return null is the requested parameter does not exist. The parameter value is retrieved from the ServletConfig object, which was given
during the init call. public Enumeration getInitParameterNames()
Returns an enumeration of names as strings of the servlets initialization parameters.
It returns an empty enumeration if there are no parameters. The parameter names are returned from the ServletConfig object, which was
provided during the init call. public ServletConfig getServletConfig()
Returns the ServletConfig object, which was provided during the init call. public void destroy()
This method is called by a service to destroy or remove a servlet from memory. A servlet developer should use the destroy method to clean up any resources used
by the servlet.
GenericServlet API (3)
public ServletContext getServletContext() Returns a ServletContext object, which contains information about the
network in which the servlet is running. The ServletContext object is retrieved from the ServletConfig object.
public String getServletInfo() Returns a string containing information about the servlet. This can include the author, version number, etc. This method is overridden by the servlet developer. Null is returned by default.
public void log(String message) Writes a message to a servlet log file along with the class name of the
servlet. The name of the servlet log file is defined by the specific web server being
used. It is normally an event log.
HttpServlet
The HttpServlet class extends the GenericServlet class.
The HttpServlet Class is abstract. The servlet developer must override at least one method.
It provides a framework for writing servlets for HTTP.
The default constructor is protected HttpServlet(). This constructor does no work.
ServletServletServletConfigServletConfig
GenericServletGenericServlet
HTTPServletHTTPServlet
HttpServlet API (1)
protected void doGet(HttpRequest req, HttpResponse resp) throws ServletException, IOException
protected void doPost(HttpRequest req, HttpResponse resp) throws ServletException, IOException
protected void doPut(HttpRequest req, HttpResponse resp) throws ServletException, IOException
protected void doDelete(HttpRequest req, HttpResponse resp) throws ServletException, IOException
protected void doOptions(HttpRequest req, HttpResponse resp) throws ServletException, IOException This method is not normally overridden unless the servlet implements
new methods not support by HTTP 1.1 protected void doTrace(HttpRequest req, HttpResponse resp) throws
ServletException IOException The default implementation returns a response with a message
containing all of the headers sent with the trace request.
HttpServlet API (2)
protected long getLastModified(HttpRequest req) Returns the time in milliseconds the requested entity was last modified. Servlets supporting GET request should override this method to provide an accurate
modification time for objects. This improves the efficiency of browsers and proxies.
protected void init() Override if initialization of other resources is required. Include the call to super.init(ServletConfig) if the method is overridden.
protected void service(HttpRequest req, HttpResponse resp) throws ServletException IOException This method performs a generic HTTP service. It is rarely overwritten.
protected void service(ServletRequest req, ServletResponse resp) throws ServletException IOException
ServletConfig Interface
This interface is implemented to pass configuration information to a servlet when it is first instantiated.
The information comes from the servlet container (JRun or, Tomcat, Java Web Server).
ServletConfig API
public String getInitParameter(String name)
Returns the string value of a given initialization parameter or null if the parameter does not exist.
public Enumeration getInitParameterNames()
Returns an enumeration of initialization parameter names or an empty enumeration if there are no initialization parameters.
public ServletContext getServletContext()
Returns a context for the servlet that provides information about the environment in which the servlet is running.
public String getServletName()
Returns a name or alias for the servlet if one has been defined via server administration. If no name has been assigned the servlets class name is returned.
ServletContext
Provides servlets with access to information about their environment (servlet container )
Also provides a logging mechanism
Useful when you are trying to debug
ServletContext API (1)
public Object getAttribute(String name) Returns the specified server container attribute or null if the attribute does not
exist. public Enumeration getAttributeNames()
Returns an enumeration of attribute names for the server context or an empty enumeration if no attribute names exist.
public String getInitParameter(String name) Returns the string value of a given context wide initialization parameter or null if
the parameter does not exist. public Enumeration getInitParameterNames()
Returns an enumeration of context wide initialization parameter names or an empty enumeration if there are no initialization parameters.
public ServletContext getServletContext(String uripath) Returns a ServletContext object that corresponds to a specified URI.
ServletContext API (2)
public int getMajorVersion() Returns the integer value of the major version of the Java Servlet API that
the servlet container supports. public String getMimeType(String file)
Returns the MIME type of the specified file or null if it is not known. public int getMinorVersion()
Returns the integer value of the minor version of the Java Servlet API that the servlet container supports.
public RequestDispatcher getNamedDispatcher(String name) Returns a RequestDispatcher object with the specified name. Returns null of no RequestDispatcher object exist in the specified path
ServletContext API (3)
public String getRealPath(String virtualpath) Returns a string contain the path of the system or real path for a specified
virtual path. public RequestDispatcher getRequestDispatcher(String path)
Returns a RequestDispatcher object specified by the path. Returns null of no RequestDispatcher object exist in the specified path.
Public URL getResource(String path) Returns a URL of a resource that is mapped to a specific path. Returns null if no resource exist at the specified path.
public InputStream getResourceAsStream(String path) Returns the resource located in the specified path as an InputStream. Returns null if no resource exist at the specified path.
public String getServerInfo() Returns the name and version of the servlet container, which the servlet is
running in.
ServletContext API (4)
public void log(String message) Writes a message to a servlet log file. The name of the servlet log file is defined by the specific web server being
used. It is normally an event log.
public void log(String message, Throwable throwable) Writes a message and a stack trace to a servlet log file.
public void removeAttribute(String name) Removes an attribute with the specified name from the servlet context.
public void setAttribute(String name, Object object) Binds an object with the specified attribute name to the servlet context.
Cookie
Represents an HTTP cookie. Cookies are used by clients to store data. Each cookie has a name and a value.
The Cookie object is usually added to an HTTP response by a Response object.
A Cookie object can be retrieved by a Request object.
The Java servlet API has also provided support for Cookies…
Cookie API (1)
public Cookie(String name, String value) Create an instance of a Cookie object with the specified name and
value. public Object clone()
Overrides the java.lang.Clone() method to return a Cookie object. public String getComment()
Returns a string describing the purpose of the cookie. Returns null if no comments have been set.
public String getDomain() Returns a string with the domain set for the cookie.
public int getMaxAge() Returns the integer value of the maximum set for a cookie. The default value is -1, indicating the cookie only exist until a browser
is closed. public String getName()
Returns the name of the cookie.
Cookie API (2)
public String getPath() Returns the path on the server where the browser returns the cookie.
public boolean getSecure() Returns true if the browser is only sending cookies over a secure
protocol such as, SSL. Returns false if the sends cookies over any protocol.
public String getValue() Returns the value of the cookie.
public int getVersion() Returns an integer value of the protocol the cookie complies with. The Java Cookie class support both Netscape version 0 and RFC 2109
version 1 cookie specifications. public void setComment(String purpose)
Allows a servlet developer to set a string describing the servlets purpose.
Cookie API (3)
public void setDomain(String domain) Allows a servlet developer to set the domain which the cookie should
be presented. This is usually the domain of the web server the servlet is running on.
public void setMaxAge(int maxage) Sets the maximum age of the cookie in seconds.
public void setPath(String uri) Sets the path on the server where the client returns the cookie.
public void setSecure(boolean flag) Indicates to the browser that the cookie should only be sent using a
secure protocol. public void setValue(String value)
Sets a new value for a cookie. public void setVersion(int version)
Sets the version of the cookie protocol that the cookie will comply with.
Session Tracking (1)
HTTP is a stateless protocol
many web applications (i.e. shopping carts) are not
need to keep track of each user’s state (i.e. items in the shopping cart)
Common techniques
user authorization
hidden form fields
URL rewriting
persistent cookies
Servlets have built-in session tracking
Session Tracking (2)
Every user has a HttpSession object
Allows an HttpRequest or HttpResponse object to store session information over multiple connections or requests for a given time period.
• i.e. shopping cart contents, database connections
Session information is only stored for the current servlet context.
Retrieve the user’s session from the HttpServletRequest:
public HttpSession getSession(boolean create)
if the user has no valid session, a new one is created if create is true; null is returned if create is false
HttpSession API (1)
public Object getAttribute(String name) Returns the object bound with the specified name, or null if no object is bound to the name.
public Enumeration getAttributeNames() Returns an Enumeration of String objects containing the attribute names of all the objects
bound to this session. public long getCreationTime()
Returns the time that the session object was created in milliseconds since midnight June 1, 1970 GMT.
public String getID() Returns a string representing the session ID. Session IDs are assigned by the servlet
container. public long getLastAccessedTime()
Returns the last time, in seconds, the client that instantiated the session object initiated an request. The time is in milliseconds since midnight June 1, 1970 GMT.
public long getLastAccessedTime() Returns the last time, in seconds, the client that instantiated the session object initiated an request. The time is in milliseconds since midnight June 1, 1970 GMT.
HttpSession API (2)
public long getMaxInactiveInterval() Returns the maximum time interval in seconds that the servlet container will keep
the session open between client accesses. public void invalidate()
Invalids the session and unbounds any objects associated to it. public boolean isNew()
Returns true if the client does not know about the session or if the client chooses not to join the session.
If a web server uses client based cookies and cookies are disabled on the browser this method would return true with each method call.
public void removeAttribute(String name) Removes the object bound with the specified name from this session.
public void setAttribute(String name, Object object) Binds an object to the session with the specified name.
public void setMaxInactiveInterval(int interval) Sets the interval value, in seconds, between client request before the servlet
contain will invalidate the session.
Session duration (1)
A unique ID is used to keep track of each session
Session tracking often implemented by the server using persistent cookies
URL rewriting used when the browser doesn’t accept cookies
Servlets need to rewrite every URL
URL left unchanged if the server doesn’t support URL rewriting
public String HttpServletResponse.encodeUrl(String url)
Session duration (2)
Sessions expire after a set period of inactivity (e.g. 30 minutes)
This is usually a configurable parameter on your servlet engine
Sessions can be invalidated by a servlet public void HttpSession.invalidate()
All data in a session object is lost when the session is removed
Persistent data should be stored externally (ie in a database)
How do we know when to save the data?
HttpSessionBindingListener
Provides a way for objects to be notified when they are bound or unbound from an HttpSession object.
The object is notified via an HttpSessionBindingEvent object. Has the following methods:
public void valueBound(HttpSessionBindingEvent event) • Notifies the object that it is being bound to a session and
identifies the session. public void valueUnbound(HttpSessionBindingEvent event)
• Notifies the object that it is being unbound to a session and identifies the session.
HttpSessionBindingEvent
The event is provided to an HttpBindingListener whenever the listener object is bound or unbound from an HttpSession value.
Methods include: public HttpSessionBindingEvent(HttpSession, String
attributename)• This is the constructor for an HttpBindingEvent object. • The input parameters specify the HttpSession object, and
the attribute name bound to an object that is being bound to the HttpSession.
public String getName() • Returns the string for the object bound to the HttpSession.
public HttpSession getSession() • Returns the HttpSession for the event.
HttpUtils
This API contains a set of static methods for getting request URLs, and parsing POST and GET requests. public static StringBuffer getRequestURL(HttpRequest)
Returns a StringBuffer with the URL that the client used to make the request. public static Hashtable parsePostData(int length, ServletInputStream in)
Parses data from an HTML POST form using the application/x-www-form-urlunencoded MIME type.
The integer input parameter is the length of the ServletInputStream. The HTML form elements have name-value pairs. These name-value pairs are inserted into the returned hashtable object If a name appears more than once the values are stored as an array of strings with the
associated key. public static Hashtable parseQueryString(String querystring)
Parses a query string passed from the client. The string is in the form n1=value&n2=value&n3=value. These name value pairs are inserted in a hashtable as key-value pairs and the hashtable is
returned. If a name appears more than once the values are stored as an array of strings with the
associated key. This method is most commonly used with HTTP GET request types.
Lifecycle of a servlet
A servlet can be created when a user invokes a URL corresponding to a servlet or when the web server is first started.
The init method is called when the first time a servlet is instantiated. Each time a user request a servlet, the servlet spawns a new thread,
unless the SingleThreadModel interface is implemented. Each time a request is made to a servlet a call is made to the service
method. The service method checks to see what type the HTTP request type (GET, POST, PUT etc.) and calls the appropriate doXXX method.
If the server needs to remove a previously loaded servlet from memory (or if the servlet engine is shutting down) a call is made to the destroy method.
Simple counter example
Setting up a request
The most common way to access a servlet is to set up an HTML form that will submit to the servlet.
<HTML><HEAD>
<TITLE>Login Page</TITLE></HEAD><BODY>
<FORM NAME = “form1” METHOD = “post” ACTION = “/servletdirectory/LoginServlet”>
<TABLE ALIGN = "center"> <TR><TH>Please Log In</TH></TR> <TR><TD><INPUT TYPE=“TEXT” NAME= “username” ></TD></TR> <TR><TD><INPUT TYPE = “password” NAME = “userpassword” ></TD></TR> </TABLE> </FORM></BODY>
</HTML>
LoginServlet example
Invoking Servlets
Directly from path http://mycompany.net:8080/servlets/Hello
From Servlet-Chaining one servlet returns a content-type that another servlet is
registered to handle (filtering) Servlets cooperate to create content Multiple servlets in a chain
• request parameters supplied to first servlet• output piped to successive servlets• last servlet in chain sends output to client
2 ways to direct server to use chains:• configure server to handle certain URLs with explicitly-
specified chains• configure server to direct certain content types to specific
servlets before output
Uses of Servlet Chaining
Quickly change appearance of a page, group of pages, or type of content
suppress <BLINK> tags
translate into French
Display section of page in special format
<SQL> tag - print results of query
Support obscure data types
serve up unsupported image formats as GIF or JPEG
HttpServlet requests and threads
Normally the system makes a single instance of a servlet and creates a new thread for each user request.
The methods and instance variables called within the doXXX methods should be synchronized if there is a need to insure access data or objects is done in a thread-safe manner.
To prevent multithreaded access to a servlet implement the SingleThreadModel interface. When this interface is implemented the system only allows
one request thread to access a servlet. If the SingleThreadModel interface is implemented request objects
should by queued and/or servlets should be pooled to decrease the impact of increased latency inherent when using the SingleThread model.
Multithreading Solutions (1)
Synchronize the doGet() method public synchronized void doGet(HttpServletRequest
req, HttpServletResponse res) servlet can’t handle more than one GET request at a
time Synchronize the critical section
PrintWriter out = res.getWriter();synchronized(this) {
count++;out.println(“This servlet has been accessed “
+ count + “ times since loading”);
}
Multithreading Solutions (2)
Store the results of the operation locallyPrintWriter out = res.getWriter();
int local_count;
synchronized(this) {
local_count = ++count;}
out.println(“This servlet has been accessed “ +
local_count + “ times since loading”);
Ignore synchronization issues (and suffer the consequences)
Java Server Pages (JSP)
Java Server Pages enable the mixing of static HTML elements with dynamically generated content from servlets on the same web page.
Using the .jsp file extension instead of the .htm or .html file extension indicates to a server that the corresponding web page has JSP elements.
JSP tags embedded in HTML pages are used to create servlets on the server side with any static HTML printed out by the servlets _jspService method.
These servlets call the service method that calls _jspService method.
There are 2 major types of JSP elements.
Scripting elements and
Directives.
JSP Scripting Elements
Expressions
are evaluated and inserted into a servlets output
Scriptlets
are inserted into the servlets _jspservice method called by the default service method.
Declarations
are inserted into the body of the servlet class, outside of any existing methods.
JSP Expressions
Expressions use the <%= %> tag format. The expression is evaluated converted into a string and
inserted into an HTML page. There are four predefined variables request (HttpRequest),
response(HttpResponse), session (HttpSession), and out (Printwriter)
Expressions are normally used for fairly short code insertion into a JSP web page. <%= request.getProtocol() %>
• Prints out “HTTP/1.1” <%= request.getRemoteAddress() %>
• Prints out the IP address of the client example “204.011.136.21”
<%= new java.util.Date %>• Prints out “Wed Apr 25 19:30:52 CDT 2001”
JSP Scriptlets
Scriplets enable the insertion of code into the servlets _jspService method.
The HTML tag format is for scriplets is in the form <% code %>.
The XML tag format is: <jsp:scriplet> </jsp:scriplet>
Fairly lengthy code can be put into Scriplets.
<% StringBuffer buf = new StringBuffer(); buf.append(“The time is now: “);
buf.append(new java.util.Date()); out.print(buf.toString()); %>
JSP Declarations
Declarations enable the definition of methods or variables that get inserted into the main body of a servlet class outside of the _jspService method that is called by service to process a request.
Declarations do not generate any output.
Declaration use the:
<%! code %> HTML tag format.
The XML tag format is:
<jsp:declaration> </jsp:declaration>
JSP Declaration example
<%! private int hitCount = 0; %>
<%! private synchronized int getPageHits(){
hitCount++;
}
%>
<%= getPageHits() %>
The hitCount integer will continue to increment
as long as the server is not rebooted.
JSP Directives
Directives enable controlling the structure of the servlet by importing classes, customizing the serlvet superclass, and inserting files into a servlet.
There are three types of Directives:
page
include
taglib.
The HTML tag format is:
<%@ type = attribute value %>.
The XML tag format is:
<jsp:directive.directive type = “attribute value” />.
Page Directives (1)
The page directive enables the JSP developer to define the following case-sensitive attributes: import
• The import attribute enables the specification of packages that should be imported by the servlet when the JSP gets translated.
• If any classes imported must have their classpath identified in the servlet container
• <%@ page import=“java.util.*” %> contentType
• The contentType attribute sets the content type of the request header.
• <%@ page contentType = “image/jpeg” %> isThreadSafe
• The isThreadSafe attribute controls whether the servlet that is translated from the JSP page is thread safe.
• When this attribute is set true the assumption is that all data and methods accessed by the JSP page are thread safe.
• <%@ page isThreadSafe=“true” %>
Page Directives (2)
session• The session attribute controls whether the JSP page will
participate in HTTP sessions.• <%@ page session = “true” %>
buffer• The buffer attribute specifies the used by the out
PrintWriter variable. For most servers the default buffer size is 8kb.
• <%@ page buffer = “32kb” %>• <%@ page buffer = “none” %>
autoflush• The autoflush attribute controls whether the output
buffer flushed when it is full or whether a buffer overflows. • A attribute value of “false” is illegal when the buffer
attribute value is set to “none”.• <%@ page autoflush = “true” %>
Page Directives (3)
errorPage• The errorPage attribute specifies a JSP page should
process any exceptions thrown but not caught in the current page. The thrown exception will be available automatically to the designated error page.
• <%@ page errorPage = relative URL %> • <%@ page errorPage = “error.html” %>
isErrorPage• The isErrorPage attribute indicates whether the current
page can act as an error page for another JSP page.• <%@ page isErrorPage = “true” %> • <%@ page isErrorPage = “false” %>
Also supports info, extends and language…
Include Directive
The JSP include directive enables the use of frames bars, table and other page elements in multiple pages. The page elements can be HTML, or JSP.
<%@ include file = “Relative URL“ %>
If the included file changes the files modification date of the file must also be changed.
The alternative <jsp:include page = “Relative URL“ flush = “true”> includes the file at the time a request is made.
However these files cannot contain JSP.
Java Beans & JSP
A bean class must have a zero argument constructor. A bean class should have no public instance variables. Persistent values should be accessed through getXXX and setXXX, or
isXXX methods <jsp.useBean id=beanName class=className /> If the bean has an interface that it implements the type attribute can
be added to the tag in the form type=someType. It can also be used to declare that the local variable a superclass of
the Bean being instantiated. <jsp:getProperty name=beanName property=beanVariable /> This tag call the the Bean’s getbeanVariable method
JSP and custom tags
Define a Java class that defines what the custom tag will do.
This class must implement the javax.servlet.jsp.tagext.Tag interface. This can be done by extending the TagSupport or BodyTagSupport classes.
Override the doStartTag method. If the tag’s action produce an output override the doEndTag method.
Custom tag XML file
Create a tag library descriptor file in XML format. This file should contain a short name for the tag library, a short
description, and a series of tag descriptions A name tag will include the name of the tag. <name> tagname</name> The tagclass tag include the name of the Java class file the defines
what the custom tag will do <tagclass>JavaClass</tagclass> An info tag contain some basic information about what the tag does. <info>This tag print out text</info> The bodycontent tag describes what type of content the tag will
output. The bodycontent can be a JSP scriplet, expression, or declaration.
<bodycontent>JSP</bodycontent>
XML file for defining a custom tag
<?xml version= “1.0” encoding=“ISO-8859-1” ?><!DOCTYPE taglib “PUBLIC //DTD JSP Tag Library 1.1// EN”><!-- the tag library descriptor --><taglib>
<tlibversion>1.0</tlibversion><jspversion>1.1<jspversion><shortname>tagfile</shortname><urn></urn><info>A custom tag library that does stuff</info>
<tag><name>supertag</name><tagclass>mytagpackage.supertagclass</tagclass><info>Doen’t do much</info><bodycontent>EMPTY</bodycontent></tag><!-- Define other tags below --></taglib>
Not just for HTML
Many programmers use servlets to assemble HTML pages, but…
Servlets can generate images using AWT, Java 2D
Servlets can generate custom data formats for use by applets and other web-aware software components
Servlets can send serialized objects to and read serialized objects from applets and other Java Platform applications
Leaving Servlets and JSPs…
The Java Servlet API allows for the generation of dynamic web pages with servlets or, dynamic elements within web pages using JSP
Combining the Java Servlet API with components of the Java API gives the application developer a totally integrated environment for developing multi-tiered web applications
…Entering Reflection
Java is more flexible
Provides a mechanism for dynamic programming – reflection
Used for
• Debuggers• Class browsers• GUI builders
What can you do with reflection?
Determine the class of an object. Get information about a class's modifiers, fields, methods,
constructors, and superclasses. Find out what constants and method declarations belong to an
interface. Create an instance of a class whose name is not known until runtime. Get and set the value of an object's field, even if the field name is
unknown to your program until runtime. Invoke a method on an object, even if the method is not known until
runtime. Create a new array, whose size and component type are not known
until runtime, and then modify the array's components.
Careful with that Ax
Don't use the reflection API when other tools more natural to the Java programming language would suffice Don’t us Method objects as a substitue for function
pointers…• Instead, you should define an interface,
and then implement it in the classes that perform the needed action.
Class
Represents, or reflects, the class.
Exists for each class
Immutable
Maintained by the Java Runtime Environment (JRE)
With the reflection API, you can invoke methods on a Class object to get return Constructor, Method, and Field objects.
Can call methods to get use these objects to get information about the corresponding constructors, methods, and fields defined in the class.
Getting the Class Object – Way 1
Invoke Object.getClass.
Need an instance of the class
Useful when you have the object, but don’t know it’s class.
Class c = mystery.getClass();
Getting the Class Object – Way 2
getSuperclass method
Retrieves the Class object for the superclass that another Class object reflects
Need an instance of Class
TextField t = new TextField();
Class c = t.getClass(); // TextField
Class s = c.getSuperclass(); // TextComponent
Getting the Class Object – Way 3
ClassName.class
Must know the name of the class at compile time
Class c = java.awt.Button.class;
Class o = Object.class;
Getting the Class Object – Way 4
Class.forName(“className”)
Class name doesn’t have to be known at compile time
Typically used to load database drivers at runtime
String s = "java.util.Date";
// can also prompt for classname
Class c = Class.forName(s);
Class Methods
Let’s take a look at some of the methods available in Class…
Write a method that, given an instance of some class, prints the names of the classes its inheritance hierarchy from least specific to most specific excluding Object
Class Modifiers
A class declaration may include the following modifiers:
public, abstract, and/or final.
The class modifiers precede the class keyword in the class definition.
int getModifiers() method in Class returns the Java language modifiers for this class or interface, encoded in an integer.
Use the isPublic, isAbstract, and isFinal static methods in Modifier to determine which modifiers exist
Class Modifiers Example
import java.lang.reflect.*;import java.awt.*;
class SampleModifier {
public static void main(String[] args) {String s = new String();printModifiers(s);
}public static void printModifiers(Object o) {
Class c = o.getClass();int m = c.getModifiers();if (Modifier.isPublic(m))
System.out.println("public");if (Modifier.isAbstract(m))
System.out.println("abstract");if (Modifier.isFinal(m))
System.out.println("final");}
}
Identifying the Interfaces Implemented by a Class
void printInterfaceNames(Object o) {Class c = o.getClass();Class[] interfaces = c.getInterfaces();
for (int i = 0; i < theInterfaces.length; i++) {String interfaceName = interfaces[i].getName();
System.out.println(interfaceName);
}}
Fields
Refers to attributes of a class
Call Class.getFields() to get an array of public fields
Call getDeclaredFields() to get an array of all fields
Let’s examine some methods in the Field class
Getting Fields
import java.lang.reflect.*;import java.awt.*;
class SampleField {
public static void main(String[] args) { GridBagConstraints g = new GridBagConstraints(); printFieldNames(g); }
static void printFieldNames(Object o) { Field[] publicFields = o.getClass().getFields(); for (int i = 0; i < publicFields.length; i++) { String fieldName = publicFields[i].getName(); Class typeClass = publicFields[i].getType(); String fieldType = typeClass.getName(); System.out.println("Name: " + fieldName + ", Type: " + fieldType); } }}
Manipulating Objects
Software development tools, such as GUI builders and debuggers, need to manipulate objects at runtime.
For example, a GUI builder may allow the end-user to select a Button from a menu of components, create the Button object, and then click the Button while running the application within the GUI builder
Setting Field Values
To modify the value of a field you have to: Create a Class object Create a Field object by invoking getField on the Class Invoke the appropriate set method on the Field object
The Field class provides several set methods. Specialized methods, such as setBoolean and setInt, are
for modifying primitive types. If the field you want to change is an object invoke the set
method.
• You can call set to modify a primitive type, but you must use the appropriate wrapper object for the value parameter
Setting Fields
static void modifyWidth(Rectangle r, Integer widthParam) {Field widthField;Integer widthValue;Class c = r.getClass();try {
widthField = c.getField("width");widthField.set(r, widthParam);
} catch (NoSuchFieldException e) {System.out.println(e);
} catch (IllegalAccessException e) {System.out.println(e);
}}
Methods
To find out what public methods belong to a class, invoke the method named getMethods.
You can use a Method object to uncover a method's name, return type, parameter types, set of modifiers, and set of throwable exceptions.
With Method.invoke, you can even call the method itself.
Let’s look at the methods available in the Method class
Steps for Invoking Methods
Create a Method object by invoking getMethod on the Class object. The getMethod method has two arguments
• A String containing the method name• An array of Class objects for the
parameters Invoke the method by calling invoke.
The invoke method has two arguments• An array of argument values to be passed
to the invoked method, • An object whose class declares or inherits
the method
Example Start
import java.lang.reflect.*;
class SampleInvoke {
public static void main(String[] args) { String firstWord = "Hello "; String secondWord = "everybody."; String bothWords = append(firstWord, secondWord); System.out.println(bothWords); }}
public static String append(String firstWord, String secondWord) { String result = null; Class c = String.class; Class[] parameterTypes = new Class[] {String.class}; Method concatMethod; Object[] arguments = new Object[] {secondWord}; try { concatMethod = c.getMethod("concat", parameterTypes); result = (String) concatMethod.invoke(firstWord, arguments); } catch (NoSuchMethodException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } return result; }
Class Constructors
Used to create instances of this class
Like methods, constructors can be overloaded and are distinguished from one another by their signatures
Call Class.getConstructors to get an array of Constructor objects.
You can use the methods provided by the Constructor class to determine the constructor's name, set of modifiers, parameter types, and set of throwable exceptions.
You can also create a new instance of the Constructor object's class with the Constructor.newInstance method.
Reflecting on Java
Reflection is a powerful tool for dynamic programming! Let’s reflect on some of the topics which we covered
this semester. There is still a plethora of Java classes and functionality
that we have not covered… Doesn’t even include the wealth of libraries available
through open source projects! Explore the Java API yourself and experiment!
References
http://java.sun.com/products/servlet/
http://java.sun.com/products/jsp/
http://java.sun.com/docs/books/tutorial/reflect/index.html
http://java.sun.com/docs/overviews/java/java-overview-1.html