Professional Documents
Culture Documents
Servlet
Programming
By Võ Văn Hải
Http://www.vovanhai.wordpress.com
1
1
14/07/2009
Component A
Component B Database
Component C
2
14/07/2009
Layered Architecture
M
I
Component A D
D
Component B L Database
E
W
Component C
A
R
E
JDBC-ODBC Bridge,
perhaps
7
Communication/ Protocols
Http Protocol
HTTP Protocol
Hypertext Transfer Protocol (HTTP) is an application level
protocol
Enables Web servers and browsers to send and receive data
HTTP Request – Client sends a request to the Web server
using HTTP request methods:
GET – Enables to access static resources
POST – Enables to access dynamic resources
HEAD – Enables to view the headers of HTTP response
HTTP Response – Web server sends response to the client
after processing the request
3
14/07/2009
10
Disadvantages
•Reduced efficiency
•Reloading Perl interpreter
11
4
14/07/2009
Servlets
Enables the user to run Java code on the
Web server
Enables to develop Web pages and process
inputs from the Web pages
Enables to add dynamic content to Web
pages
A single servlet instance can process
multiple requests
Contains built-in functionality for reading
HTML form data, handling cookies, tracking
user sessions, and setting HTTP headers
14
Example of Servlets
import java.io.*;
import Java
import javax.servlet.*;
class
import javax.servlet.http.*;
public class Example extends HttpServlet
{
public void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HTML
out.println(“<html><body>”);
code in
out.println(“ Example of Servlets”);
servlets out.println(“</body></html>”);
}
}
15
5
14/07/2009
Web.xml
<servlet>
<description></description>
<display-name>Display Servlet Name</display-name>
<servlet-name>Servlet Name</servlet-name>
<servlet-class>ServletClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet Name</servlet-name>
<url-pattern>/url_pattern</url-pattern>
</servlet-mapping>
</servlet>
16
<html>
<head>
<title>Hello World</title>
</head>
<body>
Today’s date is
<%= new java.util.Date() %>
</body>
</html>
17
6
14/07/2009
GenericServlet Class
19
HTTPServlet Class
20
21
7
14/07/2009
22
ServletRequest Interface
The ServletRequest Interface
Provides access to specific information about the request
Contains both actual request (as protocol, URL, and type) and
raw request (as headers and input stream), and client specific
request parameters (entered data on web form)
The ServletRequest Interface methods
public String getParameter(String name)
public Enumeration getParameterNames()
public String[] getParameterValues()
public Object getAttribute(String name)
public int getContentLength()
public ServletInputStream getInputStream() throws IOException
public String getServerName()
23
HttpServletRequest Interface
HttpServletRequest Interface
Extends ServletRequest Interface
Add a few more methods for handling
HTTP-specific request data
24
8
14/07/2009
getHeaders()
getHeaderNames()
25
ServletResponse Interface
The ServletResponse Interface
Create and manipulate a servlet’s output which is response to the
client
Retrieve an output stream to send data to the client, decide on the
content type ...
Define objects passed as an argument to service() method
26
HttpServletResponse interface
HttpServletResponse Interface
Extends ServletResponse
Interface
Define HttpServlet objects to
pass as an argument to the
service() method to the client
HttpServletResponse Interface
methods
◦ addCookie()
◦ addHeader()
◦ containsHeader()
◦ sendError()
27
9
14/07/2009
getOutputStream()
getWriter()
print(boolean b)
println(char c)
28
Response Header
29
Sending Header
addHeader(): add a response header with a given
name and value
addDateHeader()
addIntHeader()
containsHeader()
30
10
14/07/2009
Redirecting Requests
sendRedirect
encodeRedirectURL
31
33
11
14/07/2009
34
Initialising servlets
Need for initialising servlet context
◦ To pass parameters form client to
servlets
◦ To setup communication
Initialising servlets
◦ Container locate the servlet class
◦ Container load the servlet
◦ Create an instance of the servlet
◦ Invoke init() method to initialise the
servlet.
35
36
12
14/07/2009
RequestDispatcher (1)
forward(): used to
forward request from
one servlet to another
servlet.
37
RequestDispatcher (2)
include(): used to include the contents of
another servlet, JSP page or a HTML file to a
servlet.
38
39
13
14/07/2009
40
Reporting Errors
•public void sendError (int sc) throws IOException
•public void HttpServletResponse.setStatus (int sc)
Logging Errors: public void log (String msg[, Throwable t])
41
Logging Error
42
14
14/07/2009
RequestDispatcher dispatch =
request.getRequestDispatcher ("/Billing");
if(dispatch == null){
response.sendError (404);
}else {
dispatch.forward (request, response);
}
web.xml
<error-page>
<error-code>404</error-code>
<location>/FileNotFound.html</location>
</error-page>
43
Session Tracking
44
Session Tracking
Protocol
• Is a set of rules, which governs
the syntax, semantics and
synchronisation of
communication
• Stateless Protocol: not tracked
• HTTP Protocol
• Client – server Model
• Request – response
• Stateless Protocol
The session tracking mechanis m serves the purpose tracking the client
identity and other state information required throughout the session
45
15
14/07/2009
URL rewriting
46
47
Cookies
Is a small piece of information sent by the web server to
the client to keep track of users.
Cookie has values in the form of key-value pairs
A web browser is expected to support 20 Cookies per
host
Size of each cookie can be a maximum of 4 KB.
48
16
14/07/2009
Cookies example
//add cookie to response
Cookie cok=new Cookie("username", "vovanhai");
cok.setComment("ghi chu thu choi");
response.addCookie(cok);
49
Session Timeout:
50
HttpSession session=request.getSession(true);
if(session.isNew()){
session.setAttribute("name“,"value");
}
51
17
14/07/2009
HttpSession
session=request.getSession(true);
Object
value=session.getAttribute("name");
52
Filter
53
Filters
Components that add functionality
to the request and response
processing of a Web Application
Intercept the requests and response
that flow between a client and a
Servlet/JSP.
The Filter can
Authorize request
data
Authenticating the user,
comprising files, encrypting
data and converting images
54
18
14/07/2009
Working of Filters
55
Filters Chain
There can be more than one filter between the user and the
endpoint - Invoke a series of filters
A request or a response is passed through one filter to the
next in the filter chain. So each request and response has to
be serviced by each filter forming a filter chain
If the Calling filter is last filter, will invoke web resource
56
Configuring Filters
In Web Deployment Descriptor (web.xml)
<web-app>
….
<filter>
<icon>icon file name</icon>
<filter-name>Name of Filters</filter-name>
<display-name>displayed name</display-name>
<description>describe filter</description>
<filter-class>implemented Filter Class</filter-class>
<init-param>
<param-name>parameter name</param-name>
<param-value>value </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>FilterName</filter-name>
<url-pattern>/context</url-pattern>
</filter-mapping>
….
57 57
</web-app>
19
14/07/2009
58
FilterMapping elements
<filter-name>: name of the filter
<url-pattern>: pattern useed to resolve
URLs to which filter applies.
<servlet-name>: name of servlet whose
request and response will be serviced by
the filter
59
Configuring FilterChain
60
20
14/07/2009
Sample Filter
61
62
Security Concepts
21
14/07/2009
Pillars of Security/Security
Mechanism
Security Mechanism
Firewall
Digital Signatures
Password Authentication / Authorization
Pillars of Security
HTTP basic authentication
HTTP digest authentication
HTTPS (Secured HTTP) client authentication
Form-based authentication
64
65
66
22
14/07/2009
67 67
68
69
23
14/07/2009
Form-based Authentication
70
71
users.xml
72
24
14/07/2009
web.xml
Authentication is specified in web.xml
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/Login.jsp</form-login-page>
<form-error-page>/Error.jsp</form-error-page>
</form-login-config>
</login-config>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Managers</realm-name>
</login-config>
73
web.xml (cont)
Authentication is specified in web.xml
<security-constraint>
<web-resource-collection>
<web-resource-name>form Page</web-resource-name>
<url-pattern>/*</url-pattern> </web-resource-collection>
<auth-constraint>
<role-name>manager</role-name>
</auth-constraint>
<user-data-constraint>
<description/>
<transport-guarantee>CONFIDENTIAL</transport-
guarantee>
</user-data-constraint>
</security-constraint>
74
Declarative Security
Provides security to resource with the help of the server configuration
Works as a different layer from the web component which it works.
Advantages:
Gives scope to the programmer to ignore the constraints of the
programming environment
Updating the mechanism does not require total change in Security
model
It is easily maintainable
Limitation
Access is provided to all or denied
different page
75
25
14/07/2009
Programmatic Security
Authenticates users and grant access to the users
Servlet either authenticates the user or verify that
the user has authenticates earlier
Advantages
Ensue total portability
Allowed password matching strategies
Limitation
Much harder to code and maintain
Every resource must use the code
76
26