2. www.spiraltrain.nl
What is a Servlet?
• Java component living inside a Web Server
• Capable of communication through request-response model
• Typically a HTTP servlet generating Dynamic Web Pages
• Compares to other technologies like :
• CGI
• ASP and ASP.NET
• PHP
Java Web Applications 2
Form
HTML
internet
internet
HTML
servlet
1 2 3
6 5 4
3. www.spiraltrain.nl
Servlet Characteristics
• Possible servlet tasks :
• Read any data sent by the user :
—From HTML form, applet, or custom HTTP client
• Look up HTTP request information like browser capabilities, cookies, etc
• Generate the results from JDBC, RMI, direct computation, legacy app, etc.
• Format the results inside a document in HTML, Excel, etc.
• Set HTTP response parameters :
—MIME type, cookies, compression, etc.
• Send the document to the client
• Servlets handle multiple requests concurrently :
• Typically for each registered servlet only one instance will be loaded in memory
• Container starts a new thread for each request
• Benefits of concurrent access :
• Gives good response times
Java Web Applications 3
4. www.spiraltrain.nl Java Web Applications 4
Simple Servlet Generating HTML
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// Use "request" to read incoming HTTP headers and HTML form data
// Use "response" to specify the HTTP response status code and headers
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE HTML>n";
// Use "out" to send content to browser
out.println(docType + "<HTML>n" +
"<HEAD><TITLE>Hello Servlets</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1>Hello Servlets</H1>n" + "</BODY></HTML>");
}
}
5. www.spiraltrain.nl Java Web Applications 5
What is a Java Server Page (JSP) ?
• A JSP page uses regular HTML for most of page :
• JSP makes it easier to write, read and maintain HTML
• Dynamic content is marked with special <% and %> tags
• Actually a JSP is a representation of a servlet :
• Entire JSP page gets translated into a servlet (once)
• Servlet is what actually gets invoked (for each request)
<HTML><HEAD><TITLE>JSP declarations</TITLE></HEAD>
<BODY>
<H3>JSP declarations</H3>
<%!
java.util.Date myDate = new java.util.Date();
java.util.Date returnDate() { return myDate; }
%>
<%= returnDate() %>
</BODY>
</HTML>
6. www.spiraltrain.nl Java Web Applications 6
Benefits of JSP
• JSP supports software reuse through components :
• JavaBeans, Custom tags
• In JSP content and display logic are separated :
• Business logic in Java beans and custom tags
• Presentation logic is captured in the form of a HTML template
• JSP makes it easier to :
• Write, read and maintain the HTML
• JSP supports separation of concerns :
• Designers do the HTML layout
• Developers do the Java programming
• Automatic deployment :
• Recompile automatically when changes are made to JSP pages
• Platform-independent
7. www.spiraltrain.nl Java Web Applications 7
Translation and Request time
• At page translation time :
• JSP constructs translated into servlet code
• At request time?
• Servlet code gets executed
• No JSP interpretation occurs at request time
• Original JSP page ignored at request time
• Only servlet that resulted from it is used
• When does page translation occur?
• First time JSP page is accessed
• After modification of the JSP
• Does not occur for each request
HTTPRequest
Server
Create Source
Compile
Execute Servlet
JSP File
Changed
?
Y
N
8. www.spiraltrain.nl Java Web Applications 8
Form Submission
Name
Address
Submit Servlet
Web server
HTTP Request
POST/GET
Form data as name-
value pairs
<form action="http://host/path" method="GET">
• Get request :
• Post request :
<form action="http://host/path" method="POST">
• Pass form data as parameters hidden in request body
http://host/path?name=Bill&address=Seattle
• Pass form data as parameters by appending them in query string :
9. www.spiraltrain.nl Java Web Applications 9
POST and GET Data
• Sending form data with GET :
<form action="/MyParamsServlet">
Name : <input type = "TEXT" NAME="name"><br>
Address : <input type = "TEXT" NAME="address"><br>
<input type = "SUBMIT">
</form>
• Sending form data with POST :
<form action="/MyParamsServlet" method = "POST">
Name : <input type = "TEXT" NAME="name"><br>
Address : <input type = "TEXT" NAME="address"><br>
<input type ="SUBMIT">
</form>
• A HTML form should use POST, if it has password fields
• Size of parameters is limited to 255 characters using GET
• Parameters are read with request.getParameter("name");
10. www.spiraltrain.nl Java Web Applications 10
Sessions
• Several mechanisms used to create and track a session id
• Cookies, URL-rewriting, Hidden Form Fields
Session 1
Session 2
Server
Client 1
Client 2
Session ID 1
Session ID 2
11. www.spiraltrain.nl Java Web Applications 11
Web Applications
• Bundled together in a single directory hierarchy or file
• Servlets, JSP pages, HTML files, utility classes, beans, tag libraries, etc
• Often also packed together in WAR file
• Access to content in the Web app is always through a URL :
• URL has common prefix like http://host/webAppPrefix/blah/blah
• Deployment descriptor web.xml :
• Controls many aspects of Web application behavior
• Files in WEB-INF not directly accessible to clients :
• Server can use RequestDispatcher to forward to pages in WEB-INF
• Portability :
• All compliant servers support Web apps
• Can redeploy on new server by moving a single file
• Each Web application has its own :
• ServletContext, Class loader, Sessions, URL prefix, Directory structure
12. www.spiraltrain.nl
Web Application Structure
12
web.xml
Servlets and utility classes
.jar files, library classes bundled in jar
.tld files, tag library descriptor files
Directory for creditcard web application
Tomcat root directory for web apps
Servlets and utility classes in com package
Servlets and utility classes in com.company package
MANIFEST.MF and context.xml
html and jsp files,
CSS and image files,
Or in subdirectories
Java Web Applications
13. www.spiraltrain.nl Java Web Applications 13
Registering Web Applications
• Process is server-specific :
• Portable :
— File structure and deployment descriptor (web.xml).
• Not portable :
— The way to tell a server where a Web app is located
— The way to assign a URL prefix
• Tomcat has configurable autodeploy feature :
• Just drop directory or WAR file in install_dir/webapps
• JRun and others have similar "autodeploy" feature
• Put directory anywhere, add Context entry to install_dir/conf/server.xml
• Use administration console :
• Tomcat, JBoss, WebLogic, WebSphere
14. www.spiraltrain.nl Java Web Applications 14
WAR Files
• WAR files are simply JAR files with a different file extension :
• And JAR files are simply ZIP files
• All servers are required to support Web apps in WAR files :
• Technically, they are not absolutely required to support unbundled Web apps
• To create a WAR file :
• Change directory to top-level Web app directory
jar cvf webAppName.war *
• Or use Zip utility (or "Create Compressed Folder" on XP)
• Registering is still server-specific :
• On Tomcat just drop WAR file in install_dir/webapps
• webAppName becomes Web application URL prefix
Exercise
Deploy WAR Files
15. www.spiraltrain.nl Java Web Applications 15
Deployment Descriptor
• Filename : web.xml
• Location :
• Tomcat-specific default for all web applications install_dir/conf/web.xml
• Combined with yourWebApp/WEB-INF/web.xml
• Read : usually only when server starts
• Many servers have "hot deploy" option
• Tomcat monitors web.xml and reloads Web app when web.xml changes
• Basic format :
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd version="3.1">
<!-- "Real" elements go here. All are optional. -->
</web-app>
16. www.spiraltrain.nl Java Web Applications 16
Defining Custom URLs
• Java code :
package myPackage; ...
public class MyServlet extends HttpServlet { ... }
• web.xml entry in <web-app...>...</web-app>
• Give name to servlet :
<servlet>
<servlet-name>MyName</servlet-name>
<servlet-class>myPackage.MyServlet</servlet-class>
</servlet>
• Give address, URL mapping, to servlet :
<servlet-mapping>
<servlet-name>MyName</servlet-name>
<url-pattern>/MyAddress</url-pattern>
</servlet-mapping>
• Resultant URL :
• http://hostname/webappName/MyAddress
17. www.spiraltrain.nl 17
Servlet Initialization
• In init method through ServletConfig.getInitParameter
• init parameters typically set in web.xml
• Common to use init even when you don’t read parameters
• For complex initializations :
• Store the data in a separate file
• Use the init parameters to give the location of that file
• Example entries in web.xml :
<servlet>
<servlet-name>Counter</servlet-name>
<servlet-class>basics.Counter</servlet-class>
<init-param>
<param-name>CountFile</param-name>
<param-value>c:Tomcat 8count.dat</param-value>
</init-param>
</servlet>
Java Web Applications
18. www.spiraltrain.nl Java Web Applications 18
Application-Wide Initialization Parameters
• web.xml element : context-param
<context-param>
<param-name>support-email</param-name>
<param-value>blackhole@mycompany.com</param-value>
</context-param>
• Read with getInitParameter method of ServletContext
• Problem is who should call getInitParameter :
• load-on-startup gives partial solution
• Listeners give much better answer
19. www.spiraltrain.nl Java Web Applications 19
Loading Servlets or JSP Pages on Server Start
• What if servlet or JSP page defines data that others use?
<servlet>
<servlet-name>...</servlet-name>
<servlet-class>...</servlet-class>
<!-- Or jsp-file instead of servlet-class -->
<load-on-startup/>
</servlet>
• Specify relative order of multiple preloaded resources with :
<load-on-startup>1</load-on-startup>
<load-on-startup>2</load-on-startup>
20. www.spiraltrain.nl Java Web Applications 20
Designating Pages to Handle Errors
• Pages to use for specific HTTP status codes :
• Use the error-code element within error-page
• Pages to use when specific uncaught exceptions are thrown :
• Use the exception-type element within error-page
• Page-specific error pages :
• Use <%@ page errorPage="Relative URL" %>
— In individual JSP page, not in web.xml
<web-app...>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/NotFound.jsp</location>
</error-page>
</web-app>
21. www.spiraltrain.nl Java Web Applications 21
Other web.xml Capabilities
• You can set Web-app-wide default timeout :
<session-config>
<session-timeout>time in minutes</session-timeout>
</session-config>
• A value of 0 or negative number :
— Indicates that default sessions should never automatically time out
• If no session-config :
• Default session timeout is server-specific
• Allowing execution on multiple systems in cluster :
• Distributable
• More capabilities :
• Designating security settings
• Declaring filters
• Setting up listeners