You are on page 1of 26

14/07/2009

Servlet
Programming

By Võ Văn Hải
Http://www.vovanhai.wordpress.com
1

Developing Web Applications


An Overview

Client – Server Model

Advantages of Web Application


• Easier access to information
• Lower maintenance and deployment costs
• Platform independency
• Wider visibility
3

1
14/07/2009

Architecture of Web Applications

Traditional n-Tier Architecture

Application Logic= Presentation logic + Business Logic


(No physical demarcation between the two)

Infrastructure services provide additional functionalities required by


application, such as messaging services and transactional services.
5

Component n-tier Architecture


Interfaces

Component A

Component B Database

Component C

Application object broken into components that can communicate with


each other, through interfaces

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

Request Message structures

Response Message structures 8

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

Server Side Technologies


 Common Gateway Interface (CGI).
 Server-side JavaScript (SSJS).
 Personal Home Page (PHP).
 Java Servlet
 Active Server Page (ASP)
 Java Server Page (JSP).

10

Common Gateway Interface (CGI)


 Written using Perl programming
language

 Enables the Web server to send


information to other files and Web
browsers

 Enables to obtain information and


use it on the server machine

 Helps to process the inputs to the


form on the Web page

Disadvantages
•Reduced efficiency
•Reloading Perl interpreter
11

Active Server Pages (ASP)


 Uses server side scripting architecture that is used to develop database
driven Web applications
 Runs under Internet Information Services (IIS)
 Saved with a .asp extension
 Provides programming tools with functionalities that enable the user to
develop ASP applications faster
 Enables the user to develop Web applications using languages such as VB
Script and JScript.
 Provides an array of objects and components that provide benefits such as
speed, security, modularity, and extensibility
<%@ LANGUAGE = ”JavaScript” %> Declares page language as
<html> JavaScript
<body>
<% Response.Write(“ Welcome ”)%> Displays Welcome
</body> message
</html>
12

4
14/07/2009

PHP Hypertext Preprocessor

 Server side scripting language that provides


tools for developing dynamic Web pages
 PHP is similar to JSP and ASP
 Enables to connect the Web forms to the
database
 Requires a simple text editor to develop the
code
 Provides security by executing the PHP code on
the server
 Enables the use of PHP on operating systems,
such as, Windows, Mac, and Unix
13

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

Java Server Pages (JSP)


 JSP is a server-side technology based on servlets
 Contains static template data and JSP elements
 Enables to build cross-platform database driven Web applications
 The tag library in JSP simplifies the task of creating dynamic Web content
 Saved with a .jsp extension

<html>
<head>
<title>Hello World</title>
</head>
<body>
Today’s date is
<%= new java.util.Date() %>
</body>
</html>

17

Web Development Process


 Includes six stages:
 Planning – Implies the stage at which the user needs to gather
requirements and define target audience
 Analysis – Implies the stage at which the user needs to evaluate the
information and verify the correctness and consistency of information
 Design – Implies the stage at which the user needs to create sample
layout and send the layout for approval
 Implementation – Implies the stage at which the user needs to
establish the framework of site, create template and standard HTML
pages
 Promotion – Implies the stage at which re-engineering and re-
designing of the Web site is done
 Site maintenance and updating – Implies the stage at which bug
fixing and improvement of site is done

6
14/07/2009

GenericServlet Class

19

HTTPServlet Class

20

Web Application Directory Structure

21

7
14/07/2009

Servlet Requests and Response

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

 HttpServletRequest Interface methods


 public Cookie[] getCookies()
 public String getHeader(String
name)
 public String getMethod()
 public String getPathInfo()
 public String getAuthType()

24

8
14/07/2009

Reading Request Headers From Request


 getHeader()

 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

 The ServletResponse Interface methods


 public String getContentType()
 public PrintWriter getWriter() throws IOException
 public ServletOutputStream getOutputStream()
throws IOException
 public void setContentType(String str)

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

Sending Text & Binary data

 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

Servlet Lyfe Cycle


The life cycle is defined by:
• init() – called only one by the
server in the first request
• service() – process the client’s
request
• destroy() – called after all
requests have been processed or
a server-specific number of
seconds have passed
32

HTTP Request Processing Life


Cycle

33

11
14/07/2009

Servlets and Servlet Context

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

RequestDispatcher vs. sendRedirect


 1) If you use a RequestDispatcher, the target servlet/JSP receives
the same request/response objects as the original servlet/JSP.
Therefore, you can pass data between them using
request.setAttribute(). With a sendRedirect(), it is a new request
from the client, and the only way to pass data is through the
session or with web parameters (url?name=value).
2) A sendRedirect() also updates the browser history. Suppose you
have JSP-1 which has a form that targets Servlet-2, which then
redirects to JSP-3. With a redirect, the user's address bar will read
"http://[host]/JSP-3". If the user clicks the Reload/Refresh button,
only JSP-3 will be re-executed, not Servlet-2.
If you use a RequestDispatcher to forward from Servlet-2 to JSP-3,
the user's address bar will read "http://[host]/Servlet-2". A
reload/refresh will execute both Servlet-2 and JSP-3. This can be
important if Servlet-2 performs some system update (such as
credit-card processing).

39

13
14/07/2009

Error Handling in Servlets(1)

40

Error Handling in Servlets

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

Error Handling in Servlets


Servlet file

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

Hidden Form Fields

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);

//get & print all cookie


PrintWriter out=response.getWriter();
Cookie[]x= request.getCookies();
for(Cookie c:x)
out.println(c.getName()
+":"+c.getValue()+"<br/>");

49

Session tracking using HttpSession


 Identifying user in a multi-page request scenario and
information about that user
 Is used to created a session between the client and server
 When users make a request, the server signs it a session
object and a unique session ID
 The session ID matches the user with the session object in
subsequent requests
 The session ID and the session object are passed along
with the request to the server.

Session Timeout:

50

Storing information in a session

HttpSession session=request.getSession(true);
if(session.isNew()){
session.setAttribute("name“,"value");
}

51

17
14/07/2009

Retrieving information in session

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

 Request headers and mod ify


data
 Modify response headers and

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

Filter config example

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

Securing Web Application

62

Security Concepts

 Need of SecuringWeb Application


 Is accessed over a network such as Internet / Intranet
 Access to confidential information by unauthorized users
 Unauthorized use of resources
 Heavy traffic
 Malicious Code 63

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

HTTP Basic Authentication

65

HTTP Basic Authentication (cont)


 Common method to authenticate users by verifying the
user name and password
 Users are authenticated before allowing them to access the
protected resources.
 The server enforces security through the Web browser.
 The Web browser displays a dialog box to accept the
authentication information from the user, when the user
tries to access a protected resource.
 Credentials are passed as plaintext and could be known
easily
 Encoded using base-64 characters
 “username:password”

66

22
14/07/2009

HTTP Digest Authentication


 Use hash functions to secure web applications
 Hash function convert data into a small / complex no.
Input Hash Value
Fox DFC3478
Fox is running 583DNT89

67 67

HTTPS Client Authentication

68

HTTPS Client Authentication (cont)


 Authentication of users by establishing a Secure Sockets
Layer (SSL) connection between sender and recipient
 Sender – SSL Client
 Recipient – SSL server
 Extra authentication layer in between Http and TCP
 This layer confirms the client authentication
 Two kinds of Certificated are used
 Server Certificates
 Client Certificates

69

23
14/07/2009

Form-based Authentication

70

Form-based Authentication (cont)


 A customized login page is created for a Web
application.
 Web site users can browse the unprotected pages of the
Web site, but they are redirected to a login page when
they try to access the secured pages of the Web site.
 Use base-64 encoding, can expose user name and
password unless all connections are over SSL
 Does not specify the security realm

71

Authentication & web.xml


 Configuring Users in Tomcat
 Entering the username and password to create the

Tomcat users using View Admin Console in Tomcat


 Reference %TOMCAT_HOME%\conf\tomcat-

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

 Access is provided by the Server only if the password matches

 All the pages use same authentication mechanism

 It can not use both form-based and basic authentication for

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

You might also like