slide servlet

27
14/07/2009 1 Servlet Programming 1 By Võ Văn Hi Http://www.vovanhai.wordpress.com Developing W eb App licat ions An Overview 2 Client   Server Model Advantages of Web Application Easier access to information Lower maintenance and deplo yment costs Platform independency Wider visibility 3

Upload: nguyen-le

Post on 08-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 1/26

14/07/200

ServletProgramming

1

By VõVăn HảiHttp://www.vovanhai.wordpress.com

Developing Web ApplicationsAn Overview

2

Client – Server Model

Advantages of Web Application

• Easier access to information

• Lower maintenance and deployment costs

• Platform independency

• Wider visibility3

Page 2: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 2/26

14/07/200

Architecture of Web Applications

4

Traditional n-Tier Architecture

Application Logic= Presentation logic + Business Logic(No physical demarcation between the two)

Infrastructure services provide additional functionalities required byapplication, such as messaging services and transactional services.

5

Component n-tier Architecture

Component A

Component B

Component C

Database

Interfaces

Application object broken into components that can communicate witheach other, through interfaces

6

Page 3: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 3/26

14/07/200

Layered Architecture

Component A

Component B

Component C

Database

MIDDL

EWARE

 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 levelprotocol

Enables Web servers and b rowsers to send and receive data

HTTP Request  – Client sends a request to the Web serverusing 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 c lientafter processing the request

9

Page 4: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 4/26

14/07/200

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 programminglanguage

Enables the Web server to sendinformation to other files and Webbrowsers

Enables to obtain information anduse 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 In formation Services (IIS)

Saved with a .asp extension

Provides programming tools with func tionalities that enable the user todevelop ASP applications faster

Enables the u ser to develop Web applications using languages such as VBScript and JScript.

Provides an array of objects and components that provide benefits such asspeed, security, modularity, and extensibility

<%@ LANGUAGE = ”JavaScript” %>

<html><body><% Response.Write(“ Welcome ”)%></body></html>

Declares page language as JavaScript

Displays Welcomemessage

12

Page 5: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 5/26

14/07/200

PHP Hypertext Preprocessor

Server side scripting language that providestools 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 theWeb server

Enables to develop Web pages and processinputs from the Web pages

Enables to add dynamic content to Webpages

A single servlet instance can processmultiple requests

Contains built-in functionality for reading

HTML form data, handling cookies, trackinguser sessions, and setting HTTP headers

14

Example of Servlets

import java.io.*;import javax.servlet.*;

import javax.servlet.http.*;

public class Example extends HttpServlet

{

public void doGet(HttpServletRequest

request, HttpServletResponseresponse)

throws ServletException, IOException

{

PrintWriter out = response.getWriter();

out.println(“<html><body>”);

out.println(“ Example of Servlets”);

out.println(“</body></html>”);

}

}

import Java

class

HTMLcode inservlets

15

Page 6: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 6/26

14/07/200

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 bu ild 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 theinformation and verify the correctness and consistency of information

Design – Implies the stage at which the user needs to create samplelayout and send the layout for approval

Implementation – Implies the stage at which the user needs toestablish the framework of site, create template and st andard HTMLpages

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 bugfixing and improvement of site is done

Page 7: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 7/26

14/07/200

GenericServlet Class

19

HTTPServlet Class

20

Web Application Directory Structure

21

Page 8: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 8/26

14/07/200

Servlet Requests and Response

22

ServletRequest Interface

TheServletRequest 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 dataon web form)

TheServletRequest 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 InterfaceHttpServletRequest 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

Page 9: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 9/26

14/07/200

Reading Request Headers From Request

getHeader()

getHeaders()

getHeaderNames()

25

ServletResponse Interface

TheServletResponseInterface

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

TheServletResponseInterface methods public String getContentType()

public PrintWriter getWriter() throws IOException

public ServletOutputStream getOutputStream()

throws IOException

public void setContentType(String str)

26

HttpServletResponse interface

HttpServletResponseInterface

Extends ServletResponseInterface

Define HttpServlet objects topass as an argument to theservice() method to the client

HttpServletResponseInterfacemethods

◦ addCookie()

◦ addHeader()

◦ containsHeader()

◦ sendError()

27

Page 10: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 10/26

14/07/200

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

Page 11: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 11/26

14/07/200

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 ora server-specific number of 

seconds have passed

32

HTTP Request Processing LifeCycle

33

Page 12: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 12/26

14/07/200

Servlets and Servlet Context

34

Initialising servlets

Need for initialising servlet context

◦ To pass parameters form cli ent 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

Page 13: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 13/26

14/07/200

RequestDispatcher (1)

forward(): used toforward reque st from

one se rvl et to another

servlet.

37

RequestDispatcher (2)

include(): used to include the contents of 

another servlet, JSP page or a HTML file to aservlet.

38

RequestDispatcher vs. sendRedirect

1) If you use a RequestDispatcher, the target servlet/JSP receivesthe same request/response obj ects as the original servlet/JSP.

Therefore, you can pass data between them usingrequest.setAttribute(). With a sendRedirect(), it is a new requestfrom the client, and the only way to pass data is through thesession or with web parameters (url?name=value).

2) A sendRedirect() also updates the browser history. Suppose youhave JSP-1 which has a form that targets Servlet-2, which thenredirects 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". Areload/refresh will execute both Servlet-2 and JSP-3. This can beimportant if Servlet-2 performs some system update (such ascredit-card processing).

39

Page 14: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 14/26

14/07/200

Error Handling in Servlets(1)

40

Error Handling in Servlets

Reporting Errors

•public void sendError ( int sc) throws IOExce ption

•public void HttpServletResponse.setStatus (int sc)

Logging Errors: public void log (String msg[ , Throwa ble t])41

Logging Error

42

Page 15: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 15/26

14/07/200

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 TrackingProtocol

• Is a set of rules, which governsthe syntax, semantics and

synchronisation of 

communication

• Stateless Protocol: not tracked

• HTTP Protocol

• Client  – server Model

• Request  – response

• Stateless Protocol

The sess ion tracking mechanism serves the purpose tracking the client

identity and other state information required throughout the session

45

Page 16: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 16/26

14/07/200

URL rewriting

46

Hidden Form Fields

47

Cookies Is a small piece of information sent by the web server to

theclient to keep trackof users.

Cookiehas valuesin the formof key-value pairs

A web browser is expected to support 20 Cookies per

host

Size ofeach cookiecan be a maximumof 4 KB.

48

Page 17: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 17/26

14/07/200

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

informationabout thatuser

Isusedto created a sessionbetween theclient and server

When users make a request, the server signs it a session

object anda unique sessionID

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 requestto theserver.

Session Timeout:

50

Storing information in a session

HttpSession session=request.getSession(true);

if(session.isNew()){

session.setAttribute("name“,"value");

}

51

Page 18: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 18/26

14/07/200

Retrieving information in session

HttpSessionsession=request.getSession(true);

Objectvalue=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

t hat flow bet we en a c lient and a

Servlet/JSP.

The Filter can

Authorize request

Request headers and modify

data

Modify response headers and

data

Authenticat ing the user,

comprising files, encrypting

data and converting images

54

Page 19: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 19/26

14/07/200

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

beserviced by each filter forminga filter chain

If the Callingfilteris lastfilter, will invokeweb resource

56

Configuring Filters

57

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>

<des cription>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>

….

</we b-a >57

Page 20: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 20/26

14/07/200

2

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 bythe filter

59

Configuring FilterChain

60

Page 21: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 21/26

14/07/200

2

Sample Filter

61

Securing Web Application

62

Security Concepts

Needof SecuringWeb Application

Isaccessed over a network such asInternet / Intranet

Access to confidential information by unauthorized users

Unauthorized use of resources

Heavy traffic

Malicious Code 63

Page 22: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 22/26

14/07/200

2

Pillars of Security/Security

Mechanism SecurityMechanism

Firewall

Digital Signatures PasswordAuthentication / Authorization

Pillarsof 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 nameand password

Users are authenticated before allowing them to access the

protectedresources.

Theserver enforcessecuritythroughthe Web browser.

The Web browser displays a dialog box to accept the

authentication information from the user, when the user

triesto accessa protected resource.

Credentials are passed as plaintext and could be known

easily

Encodedusingbase-64characters

“username:password”

66

Page 23: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 23/26

14/07/200

2

HTTP Digest Authentication

67

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

HTTPS Client Authentication

68

HTTPS Client Authentication (cont)Authentication of users by establishing a Secure Sockets

Layer (SSL) connectionbetweensenderand recipient

Sender – SSL Client

Recipient – SSL server

Extra authentication layer in between Http and TCP

This layer confirms the client authentication

Two kinds of Certi ficated are used

Server Certificates

Client Certificates

69

Page 24: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 24/26

14/07/200

2

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.xmlConfiguring 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

Page 25: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 25/26

14/07/200

2

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 t o the programmer to ignore the constraints of the

programming environment

Updat ing the mechanism d oes not require total change in Security

model

It is easily mainta inable

Limitat ion

Access is provided to all or denied

Access is provided by the Server only if the password matches

All the pages use same authent ication mechanism

It can not use both form-based and basic authent ication for

different page

75

Page 26: Slide Servlet

8/7/2019 Slide Servlet

http://slidepdf.com/reader/full/slide-servlet 26/26

14/07/200

Programmatic Security

Authenticates users and grant access to the users

Servlet either authenticates the user or verify that

the user has authenticates earlierAdvantages

Ensue total portability

Allowed password matching strategies

Limitation

Much harder to code and maintain

Every resource must use the code

76