Advanced Topics in Java
Advanced Topics in Java
Overview
• Web Applications
• Servlet Model/ Architecture
• Servlet Container and Servlet Life Cycle
• Creating Servlets
– Interface Servlet and class HttpServlet
– HTTP methods
• Deploying Servlets
– Web Application Structure
– Customizing the Servlet: web.xml
• Using Servlets
– HTML Forms
– GET and POST requests
• Handling requests: ServletRequest/HttpServletRequest
• Sending responses: ServletResponse/HttpServletResponse
• Servlet Configuration: ServletConfig
• Servlet Context: ServletContext
Servlet Container
• A servlet container (also called a servlet engine) is a separate module used by the web
server to load and run servlets.
• We will use Tomcat (5.5.x) (http://jakarta.apache.org/tomcat/) -- which can be
run standalone, as a web server and a servlet container integrated into a single
program.
– implements Java API Servlet 2.4 and JSP (Java Server Pages) 2.0 specification
(http://jcp.org/en/jsr/detail?id=154, http://jcp.org/en/jsr/
detail?id=152)
• Some other servlet containers: Resin, JRun, Weblogic, WebSphere.
ATIJ Core Servlets 3/57
Practical Considerations
• Install Tomcat (5.5.x) (http://jakarta.apache.org/tomcat/).
• Set environment variables (Windows):
TOMCAT_HOME = C:\jakarta-tomcat-5.5.x
CATALINA_HOME = C:\jakarta-tomcat-5.5.x
JAVA_HOME = C:\Program Files\Java\jdk1.5.0_y
CLASSPATH = .;%TOMCAT_HOME%\common\lib\servlet-
api.jar;%TOMCAT_HOME%\common\lib\jsp-api.jar
• Use Tomcat Manager (http://hostname/manager/html).
– To start, stop and reload.
– Requires user authentication.
• Reference the Servlet API doc:
– http://hostname/tomcat-docs/index.html
– C:\jakarta-tomcat-5.5.x\webapps\tomcat-docs\servletapi\index.html
Internet / Http
Web Server
File
Servlet Container Database
System
*.html Servlet
Web-based Application
http://www.ii.uib.no/~khalid/index.html
• An active resource has processing capabilities. The result of the processing (dynamic
content) is returned to the client.
For example: servlets and JSP scripts.
http://www.google.com/search?sourceid=navclient&ie=UTF-8&q=servlet+jsp
«interface» ...
Servlet
«abstract» «abstract»
GenericServlet HttpServlet
«interface» «interface»
ServletRequest HttpServletRequest
«interface» «interface»
ServletResponse HttpServletResponse
«interface» «interface»
ServletConfig HttpSession
«interface»
ServletContext Cookie
...
ServletException
configuration:
ServletConfig
context:
ServletContext
How the objects in the above diagram function and interact is essential to developing and
deploying servlets.
Web Server
File
System Database
*.html
• Depending on the HTTP method in the request, the corresponding servlet method is
invoked.
• The default implementation of a doHttpRequestMethodName() method returns a
HttpServletResponse.SC_BAD_REQUEST response (error code 400).
• The servlet should override the appropriate request handling methods depending on
the business logic.
ATIJ Core Servlets 15/57
Servlet States
• Before a servlet can process requests, it must be
loaded by the servlet container. [load]
[not initialized]
• The servlet container loads and instantiates the Instantiated
servlet class.
• The servlet is initialized once during its life time. Initialized
As part of the initialization, the init() method
of the servlet is also called.
Servicing
• Once instantiated and loaded, the servlet is
[destroy]
ready for servicing requests. This ultimately [request]
involves one of the servlet methods
doHttpRequestMethodName() to handle the
request. Each request is executed in a separate
thread.
• Several threads can share the servlet
• When no longer needed, the servlet is destroyed instance. Thus, fields cannot be
by the servlet container. Before destroying the assumed to be thread-safe.
servlet, the container calls the destroy()
method of the servlet.
• The following methods supply protocol-, method- and path-related information in the
request:
String getMethod() Returns the name of the HTTP method in this request. For
example: GET, POST, or HEAD.
String getScheme() Returns the name of the scheme used to make this request, for
example, http or ftp.
String getProtocol() Returns the name and version of the protocol used in the
request. The form is protocol/majorVersion.minorVersion, for
example, HTTP/1.1.
StringBuffer getRequestURL() Reconstructs the URL the client used to make the request.
String getRequestURI() Returns the part of URL in this request that follows the host
and port number up to the query string in the method line.
String getServletPath() Returns the part of the URL that calls the servlet.
String getContextPath() Returns the portion of the request URI that indicates the
context of the request. The context path always comes first in a
request URI. The path starts with a "/" character but does not
end with a "/" character.
Requested URL
• The following methods supply information about the headers in the request:
String getHeader(String name) Returns the String value of the specified header name.
int getIntHeader(String name) Returns the int value of the specified header name.
Enumeration getHeaders(String name) Returns an enumerator of Strings containing all the
values associated with the specified header name.
Enumeration getHeaderNames() Returns an enumerator of Strings containing all the
header names.
• The following methods supply information about the client request parameters
submitted in the request:
String getParameter(String name) Returns one value for the parameter name if specified
in the request, null otherwise.
Note a parameter name can have several values
associated with it.
String[] getParameterValues( Returns all the values for the parameter name if
String name) specified in the request, null otherwise.
Enumeration getParameterNames() Returns an enumerator of Strings containing the
parameter names.
• The HttpServletResponse interface provides constants for the HTTP status codes:
HttpServletResponse.SC_OK // HTTP Status-Code 200: OK
HttpServletResponse.SC_NOT_FOUND // HTTP Status-Code 404: Not Found
HttpServletResponse.SC_NOT_IMPLEMENTED // HTTP Status-Code 501: Not Implemented
myCompany
MyClass.class
lib Other necessary JAR archives
*.jar
Implementing a Servlet
• When overriding a doHttpRequestMethodName() method, the following procedure is
recommended:
– Read the request data.
– Write the response headers.
– Get the response's writer or output stream object.
– Write the response data.
• In the response, include content type and encoding.
• When using a PrintWriter object to return the response, set the content type before
accessing the PrintWriter object.
• The servlet container must write the headers before committing the response, because
in HTTP the headers must be sent before the response body.
– Committing locks some of the features of the servlet, this is specially true with
respect to the response.
• A common strategy is to write the response data to an internal stream, and dump this
data out to the output stream which is only closed after all data has been flushed.
• Since several threads (one for each request) can be executing the servlet, normal
thread-safety precautions apply.
<display-name>myExamples</display-name>
<!-- A servlet element -->
<servlet> A servlet element is specified for each servlet
<servlet-name>mySimpleServlet</servlet-name>in the web application. The servlet name is
used to identify pertinent information about
<servlet-class>StopTheWorld</servlet-class>
the servlet, for example its class.
</servlet>
– For example, the myExamples web application has the following context:
<Context
path="/myExamples"
docBase="/myExamples"
reloadable="true"
workDir="/webapps/myExamples/work">
</Context>
• If the class files or the deployment descriptor file change, the web application
structure must be updated with the new files.
– If the application is reloadable, Tomcat will update the files.
– However, it might be necessary to stop and restart the web application, and at
times to restart the web server.
<servlet-mapping>
<servlet-name>SimpleHoroscope</servlet-name>
<url-pattern>/SimpleHoroscope</url-pattern>
</servlet-mapping>
...
out.print("<h3>Request Parameters</h3>");
out.print("<p>");
Enumeration enumerator = req.getParameterNames();
while (enumerator.hasMoreElements()) {
String paramName = (String) enumerator.nextElement();
String paramValue = req.getParameter(paramName);
out.print(paramName + ": " + paramValue + "<br>");
}
out.println("</p>");
}
HTTP Request
Illustrating:
• Method- and Path-related
Information
• Request Headers
• Request Parameters
web.xml SimpleHoroServlet.class
...
<servlet>
...
<servlet-name>
SimpleHoroscope
</servlet-name>
<servlet-class>
SimpleHoroServlet
</servlet-class>
</servlet>
...
<servlet-mapping>
<servlet-name>
SimpleHoroscope
</servlet-name>
<url-pattern>
/SimpleHoroscope
</url-pattern>
</servlet-mapping>
...
• The ServletContext object is contained within the ServletConfig object, which the
server provides the servlet when the servlet is initialized.
• For a servlet container that is in a single JVM, every web application running in the
container has exactly one servlet context.
This servlet context is shared by the web components of the web application.
// The signs.
private String[] horoscopeSign = { "aquarius", "pisces", "aries", "taurus",
"gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius",
"capricorn" };