You are on page 1of 22

01/10/2010

Focus
 Application Model
 Servlet Requests and Response
Servlet  Servlets and Servlet Context
 Session Tracking
Programming  Filter
 Securing Web Application

By Võ Văn Hải
http://vovanhai.wordpress.com
1 2

Client – Server Model

Developing Web Applications


An Overview

Advantages of Web Application


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

1
01/10/2010

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 6

Component n-tier Architecture Layered Architecture


Interfaces

Component A

Component B Database M
I
Component C Component A D
D
Component B L Database
E
W
Application object broken into components that can communicate with Component C
A
each other, through interfaces R
E
JDBC-ODBC Bridge,
perhaps
7 8

2
01/10/2010

Communication/ Protocols
HTTP Protocol
 Hypertext Transfer Protocol (HTTP) is an application level
protocol
 Enables Web servers and browsers to send and receive data
Http Protocol  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
Request Message structures

Response Message structures 9 10

Server Side Technologies


Common Gateway Interface (CGI)
 Common Gateway Interface (CGI).  Written using Perl programming
 Server-side JavaScript (SSJS). language

 Enables the Web server to send


 Personal Home Page (PHP). information to other files and Web
browsers
 Java Servlet
 Enables to obtain information and
 Active Server Page (ASP) use it on the server machine

 Helps to process the inputs to the


 Java Server Page (JSP). form on the Web page

Disadvantages
•Reduced efficiency
•Reloading Perl interpreter
11 12

3
01/10/2010

Active Server Pages (ASP) PHP Hypertext Preprocessor


 Uses server side scripting architecture that is used to develop database
driven Web applications
 Runs under Internet Information Services (IIS)  Server side scripting language that provides
 Saved with a .asp extension tools for developing dynamic Web pages
 Provides programming tools with functionalities that enable the user to  PHP is similar to JSP and ASP
develop ASP applications faster
 Enables to connect the Web forms to the
 Enables the user to develop Web applications using languages such as VB
Script and JScript.
database
 Provides an array of objects and components that provide benefits such as
 Requires a simple text editor to develop the
speed, security, modularity, and extensibility code
<%@ LANGUAGE = ”JavaScript” %> Declares page language as  Provides security by executing the PHP code on
<html> JavaScript the server
<body>
<% Response.Write(“ Welcome ”)%> Displays Welcome  Enables the use of PHP on operating systems,
</body> message such as, Windows, Mac, and Unix
</html>
13 14

Servlets
Example of Servlets
import java.io.*;
 Enables the user to run Java code on the import Java
import javax.servlet.*;
Web server class
import javax.servlet.http.*;
public class Example extends HttpServlet
 Enables to develop Web pages and process {
public void doGet(HttpServletRequest
inputs from the Web pages request, HttpServletResponse response) throws
 Enables to add dynamic content to Web ServletException, IOException{
PrintWriter out = response.getWriter();
pages HTML out.println(“<html><body>”);
 A single servlet instance can process code in
servlets
out.println(“ Example of Servlets”);
out.println(“</body></html>”);
multiple requests }
 Contains built-in functionality for reading }
public void init(ServletConfig config) throws
HTML form data, handling cookies, tracking ServletException {
user sessions, and setting HTTP headers super.init(config);
String param =
config.getInitParameter(“param");
}
15 16

4
01/10/2010

Web.xml Java Server Pages (JSP)


<servlet>
<description></description>  JSP is a server-side technology based on servlets
<display-name>Display Servlet Name</display-name>  Contains static template data and JSP elements
<servlet-name>Servlet Name</servlet-name>  Enables to build cross-platform database driven Web applications
<servlet-class>ServletClass</servlet-class>  The tag library in JSP simplifies the task of creating dynamic Web content
<init-param>
 Saved with a .jsp extension
<param-name>param</param-name>
<param-value>Value of param</param-value> <html>
<head>
</init-param>
<title>Hello World</title>
</servlet> </head>
<servlet-mapping> <body>
Today’s date is
<servlet-name>Servlet Name</servlet-name> <%= new java.util.Date() %>
<url-pattern>/url_pattern</url-pattern> </body>
</servlet-mapping> </html>

</servlet>
17 18

GenericServlet Class
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

20

5
01/10/2010

HTTPServlet Class Web Application Directory Structure

21 22

ServletRequest Interface
 The ServletRequest Interface
 Provides access to specific information about the request
 Contains both actual request (as protocol, URL, and type) and
Servlet Requests and Response 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()
 Public void setAttribute(String name, Object value)
23 24

6
01/10/2010

HttpServletRequest Interface Reading Request Headers From Request


 HttpServletRequest Interface
 Extends ServletRequest Interface
 getHeader()
 Add a few more methods for handling
HTTP-specific request data

 getHeaders()
 HttpServletRequest Interface methods
 public Cookie[] getCookies()
 public String getHeader(String
name)  getHeaderNames()
 public String getMethod()
 public String getPathInfo()
 public String getAuthType()

25 26

ServletResponse Interface HttpServletResponse interface


 The ServletResponse Interface  HttpServletResponse Interface
 Create and manipulate a servlet’s output which is response to the  Extends ServletResponse
client Interface
 Retrieve an output stream to send data to the client, decide on the  Define HttpServlet objects to
content type ... pass as an argument to the
service() method to the client
 Define objects passed as an argument to service() method
 HttpServletResponse Interface
 The ServletResponse Interface methods methods
 public String getContentType() ◦ addCookie()
 public PrintWriter getWriter() throws IOException ◦ addHeader()
 public ServletOutputStream getOutputStream() ◦ containsHeader()
throws IOException ◦ sendError()
 public void setContentType(String str)

27 28

7
01/10/2010

Sending Text & Binary data Response Header

 getOutputStream()

 getWriter()

 print(boolean b)
 println(char c)
29 30

Sending Header Redirecting Requests


 addHeader(): add a response header with a given  sendRedirect
name and value

 addDateHeader()

 addIntHeader()  encodeRedirectURL

 containsHeader()

31 32

8
01/10/2010

Generic Servlet Lyfe Cycle HTTP Request Processing Life 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
33 34

Initialising servlets
 Need for initialising servlet context
◦ To pass parameters form client to
servlets
◦ To setup communication
Initialising servlets
Servlets and Servlet Context 
◦ Container locate the servlet class
◦ Container load the servlet
◦ Create an instance of the servlet
◦ Invoke init() method to initialise the
servlet.

35 36

9
01/10/2010

RequestDispatcher (1)
 forward(): used to
forward request from
one servlet to another
servlet.

37 38

RequestDispatcher (2) RequestDispatcher vs. sendRedirect


1) If you use a RequestDispatcher, the target servlet/JSP receives
 include(): used to include the contents of 
the same request/response objects as the original servlet/JSP.
another servlet, JSP page or a HTML file to a Therefore, you can pass data between them using
request.setAttribute(). With a sendRedirect(), it is a new request
servlet. 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 40

10
01/10/2010

Error Handling in Servlets


Error Handling in Servlets(1)

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 42

Error Handling in Servlets


Logging Error
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 44

11
01/10/2010

Session Tracking
Protocol
• Is a set of rules, which governs
the syntax, semantics and
synchronisation of
Session Tracking communication
• Stateless Protocol: not tracked
• HTTP Protocol
• Client – server Model
• Request – response
• Stateless Protocol

The session tracking mechanism serves the purpose tracking the client
identity and other state information required throughout the session
45 46

URL rewriting Hidden Form Fields

47 48

12
01/10/2010

Cookies Cookies example


 Is a small piece of information sent by the web server to //add cookie to response
the client to keep track of users. Cookie cok=new Cookie("username", "vovanhai");
 Cookie has values in the form of key-value pairs cok.setComment("ghi chu thu choi");
 A web browser is expected to support 20 Cookies per response.addCookie(cok);
host
 Size of each cookie can be a maximum of 4 KB. //get & print all cookie
PrintWriter out=response.getWriter();
Cookie[]x= request.getCookies();
for(Cookie c:x)
out.println(c.getName()
+":"+c.getValue()+"<br/>");

49 50

Session tracking using HttpSession Storing information in a session


 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 HttpSession session=request.getSession(true);
with the request to the server. if(session.isNew()){
session.setAttribute("name“,"value");
Session Timeout: }

51 52

13
01/10/2010

Retrieving information in session

Filter
HttpSession
session=request.getSession(true);
Object
value=session.getAttribute("name");

53 54

Filters Working of 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 modify


data
 Modify response headers and

data
 Authenticating the user,
comprising files, encrypting
data and converting images
55 56

14
01/10/2010

Filter Example
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

57 58

Filter config example

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>
….
59 59 60
</web-app>

15
01/10/2010

Configuring FilterChain
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

61 62

Modifying Character Encoding sample

Securing Web Application

63 64

16
01/10/2010

Security Concepts Pillars of Security/Security


Mechanism
 Security Mechanism
 Firewall
 Digital Signatures
 Password Authentication / Authorization
 Pillars of Security
 HTTP basic authentication
 HTTP digest authentication
 Need of Securing Web Application  HTTPS (Secured HTTP) client authentication
 Is accessed over a network such as Internet / Intranet  Form-based authentication
 Access to confidential information by unauthorized users
 Unauthorized use of resources
 Heavy traffic
 Malicious Code 65 66

HTTP Basic Authentication 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”

67 68

17
01/10/2010

HTTP Digest Authentication HTTPS Client 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

69 69 70

HTTPS Client Authentication (cont) Authentication & web.xml


 Authentication of users by establishing a Secure Sockets  Configuring Users in Tomcat
Layer (SSL) connection between sender and recipient  Entering the username and password to create the

 Sender – SSL Client Tomcat users using View Admin Console in Tomcat
 Recipient – SSL server  Reference %TOMCAT_HOME%\conf\tomcat-

 Extra authentication layer in between Http and TCP users.xml


 This layer confirms the client authentication
 Two kinds of Certificated are used
 Server Certificates
 Client Certificates

71 72

18
01/10/2010

HTTP Basic Authentication demo HTTP Digest Authentication demo

73 74

Form-based Authentication 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

75 76

19
01/10/2010

web.xml (cont.)
web.xml

or INTEGRAL

oINTEGRAL requires data must be guaranteed not to change in transit.


oCONFIDENTIAL requires data must be guaranteed not to have bean read by
an unauthorized thrid party in transit.
oA CONFIDENTIAL guarantee implies INTEGRAL.
77 78

Configure SSL in Tomcat Form-based Authentication with Tomcat User


Enable this XML fragment in Tomcat server.xml

Run keytool to generate key-stroke:

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg


RSA
Default password is changeit

79 80

20
01/10/2010

Declarative Security Programmatic Security


 Provides security to resource with the help of the server configuration
 Works as a different layer from the web component which it works. Authenticates users and grant access to the users
 Advantages: Servlet either authenticates the user or verify that
 Gives scope to the programmer to ignore the constraints of the

programming environment
the user has authenticates earlier
 Updating the mechanism does not require total change in Security Advantages
model
 Ensue total portability
 It is easily maintainable

 Limitation
 Allowed password matching strategies
 Access is provided to all or denied Limitation
 Access is provided by the Server only if the password matches
 Much harder to code and maintain
 All the pages use same authentication mechanism
 Every resource must use the code
 It can not use both form-based and basic authentication for

different page

81 82

Any questions?

83 84

21
01/10/2010

That’s about all for today!

Thank you all for your attention and patient!

22

You might also like