® IBM Software Group © 2007 IBM Corporation Servlet Filtering 4.1.0.3.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
JSP and Servelets.
COMP 321 Week 13. Overview Filters Scaling and Remote Models MVC and Struts.
Dispatching, monitoring, filtering
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
MC365 Application Servers: Servlets. Today We Will Cover: What a servlet is The HTTPServlet and some of its more important methods How to configure the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Session-02.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
UNIT-V The MVC architecture and Struts Framework.
Lecture 2 - Struts ENTERPRISE JAVA. 2 Contents  Servlet Deployment  Servlet Filters  Model View Controllers  Struts  Dependency Injection.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 Web Developer & Design Foundations with XHTML Chapter 6 Key Concepts.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
1 Chapter 2 The Web Tier  Web Applications and Web ContainersWeb Applications and Web Containers  Dynamic Content CreationDynamic Content Creation 
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
Servlet / JSP 전 혜 영전 혜 영 전 혜 영전 혜 영. 0. 목차  Web Application Technologies  Servlet Server  Simple Servlet  Servlet / HTML Form  Deployment Descriptor.
CGS – 4854 Summer 2012 Web Site Construction and Management Instructor: Francisco R. Ortega Chapter 2.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
1 JSP with Custom Tags Blake Adams Introduction Advanced Java Server Pages – Custom Tags Keyterms: - Tag Library Descriptor(TLD) - Tag Libraries.
® IBM Software Group © 2007 IBM Corporation Servlet Listeners
Java Servlets & Java Server Pages Lecture July 2013.
JSP Filters 23-Oct-15. JSP - FILTERS A filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
CSC 2720 Building Web Applications Frameworks for Building Web Applications.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Servlet Filters import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TimerFilter implements Filter { /* J2EE v1.3 Filter.
Copyright © 2002 ProsoftTraining. All rights reserved. Java Servlets.
Servlet Filters JAVA Enterprise Edition. Servlet Filters Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
Java Enterprise Edition Programming Page 1 of 9Configuring Servlets Web Application Context Name  In multiple web applications, a “context name” is used.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
13 Copyright © 2004, Oracle. All rights reserved. Adding Validation and Error Handling.
11 Copyright © 2004, Oracle. All rights reserved. Customizing Actions.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Chapter 4 Request and Response. Servlets are controlled by the container.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Securing Web Applications Lesson 4B / Slide 1 of 34 J2EE Web Components Pre-assessment Questions 1. Identify the correct return type returned by the doStartTag()
17 Copyright © 2004, Oracle. All rights reserved. Integrating J2EE Components.
Spell Checker web service (you build a web client that interacts with the service) The client uses a servlet class and a JSP page. The user passes information.
Net-centric Computing Servlets & JSP. Lecture Outline  Tracking Sessions  Cookies  Examples  JSP  Differences between JSP and Servlets  JSP Constructs.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Struts 2 Development. Topics  Roles in Struts Development  Control Flow  Actions  Struts 2 Views and Target  Struts 2 Custom Tags  Validation 
Introduction to Servlets
Java Servlets By: Tejashri Udavant..
Pre assessment Questions
Servlets Hits Counter 20-Jul-18.
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Knowledge Byte In this section, you will learn about:
Knowledge Byte In this section, you will learn about:
CS3220 Web and Internet Programming Introduction to Java Servlets
Pre-assessment Questions
Presentation transcript:

® IBM Software Group © 2007 IBM Corporation Servlet Filtering

2 After completing this unit, you should be able to:  Describe the processing flow for filters  List the Servlet API interfaces and support object used to implement filters  Create a new filter using Rational Application Developer  Create deployment descriptor entries for a filter  Develop a basic filter using the appropriate interfaces  Develop a filter that blocks normal filter chain execution  Develop a filter using a wrapped custom response object After completing this unit, you should be able to:  Describe the processing flow for filters  List the Servlet API interfaces and support object used to implement filters  Create a new filter using Rational Application Developer  Create deployment descriptor entries for a filter  Develop a basic filter using the appropriate interfaces  Develop a filter that blocks normal filter chain execution  Develop a filter using a wrapped custom response object Unit objectives

3 Introducing Filters  Reusable components  Transform (or filter) the content of HTTP requests, responses, and headers  Can be configured into chains of multiple filters  Are indirectly invoked by client request for a Web resource  Requested Web resource is at the end of the chain  Types of functionality:  Process the request for a resource before it is invoked  Process the response for a resource after it is invoked  Modify the response or request object for a Web resource by wrapping the objects in a custom object  Transfer control to next filter or Web resource in chain  Block execution of the filter chain

4 Typical Uses of Filters  The Servlet Filtering Specification notes the following as examples of typical filter uses:  Authentication filters  Logging and auditing filters  Image conversion filters  Data compression filters  Encryption filters  Tokenizing filters  Filters that trigger resource access events  XSLT filters to transform XML content  MIME-type chain filters  Caching filters

5 Filter Processing Flow Web Resource Requested by Client RequestResponse Access/Modify Request doFilter() Access /Modify Response Filter Client Request for Web Resource Container

6 Filter Chain Processing  Filters can be configured in a chain  A FilterChain object describes the chain  Filters are invoked via nested calls  Web container invokes doFilter() in first filter in chain  Class: Implementation of javax.servlet.Filter  Parameters: –Request of type ServletRequest –Response of type ServletResponse –Chain of type FilterChain  First filter in chain calls doFilter() to invoke next filter in chain  Referenced from input FilterChain object  Class: javax.servlet.FilterChain  Parameters: –Request of type ServletRequest –Response of type ServletResponse  Last entry in the chain is the Web resource

7 doFilter() Nested Calls doFilter() { chain.doFilter() } doPost() { …… ……. } doFilter() { chain.doFilter() } FirstFilter SecondFilter FilteredServlet Request Response

8 Typical doFilter() Pattern  Examine request object  Possibly wrap request or response object in new custom object  Invoke next filter in chain with doFilter() method  Possibly with wrapped objects  May end chain by not performing this step  Filter must complete response object  Process response object

9 Implementing a Filter  Create a class that implements the javax.servlet.Filter interface  Implement methods:  init()  doFilter()  destroy()  Describe the filter in the deployment descriptor with the filter element  Configure the filter’s chaining configuration in the deployment descriptor with the filter-mapping element

10 Application Developer Filter Support  Creating a filter in Web Perspective  Right-click on the Web project and click New  Filter  Creates a class that implements javax.servlet.Filter  Creates the following methods in the class:  init  doFilter  destroy  Creates entries in deployment descriptor to define filter:  filter  filter-mapping

11 Creating a New Filter in Application Developer Click Next

12 The javax.servlet.Filter Interface  Three methods comprise the interface:  init() throws ServletException  Purpose: To perform filter initialization  Called by container to indicate filter is being placed in service  Parameter: –config of type FilterConfig  doFilter() throws ServletException, IOException  Purpose: To perform the filtering  Called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain  Parameters: –Request of type ServletRequest –Response of type ServletResponse –Chain of type FilterChain  destroy()  Purpose: To perform filter cleanup.  Called by container to indicate filter is being placed out of service  No parameters

13 The javax.servlet.FilterConfig Interface  There are four getter methods in the interface:  getFilterName()  Returns the String name of the filter  getInitParameter()  Returns the the String value of a initialization parameter  Input: name of type String  getInitParameterNames()  Returns an enumeration of String with the names of the initialization parameters  getServletContext()  Returns a reference to the ServletContext in which the filter is operating

14 The javax.servlet.FilterChain Interface  The interface consists of one method:  doFilter() throws ServletException  Purpose: invoke the next filter in the chain  Called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain  Inputs: –Request of type ServletRequest –Response of type ServletResponse

15 Describing the Filter  Filters are described in the deployment descriptor (web.xml)  Structure of the filter’s describing elements  : describes the filter  : name of the filter  : name of the implementing class  : describes initialization parameters of the filter – : the initialization parameter name – : the initialization parameter value

16 Example of a Filter Description FormChecker com.ibm.filters.FormChecker __FORM_NAME Prime Finder num Number

17 Describing the Filter Mapping  Filter mappings are described in the deployment descriptor (web.xml)  Structure of the filter’s mapping elements  : describes the filter  : name of the filter to be mapped  : name of the resource to apply this filter OR  : URL pattern of the resource to apply this filter

18 Examples of Filter Mapping Logger Prime WelcomeTrailer /Welcome.jsp

19 Configuring Filters with Application Developer  Configure filters in the Web Deployment Descriptor Editor  Filters tab  Source tab

20 Configuring Filter Chaining  Determined by order of filter-mapping elements in the deployment descriptor  Last filter in chain invokes the requested Web resource  Rules:  First, get filters that match url-pattern element of requested Web resource  Second, get filters that match servlet-name element of requested Web resource  In each case, the filter’s order in the chain is determined by its order in the deployment descriptor file

21 Example of Configuring Filter Chaining FormChecker Prime Logger /* PrimeTrailer Prime Mapping Order for Prime Servlet: (1) Logger (2) FormChecker (3) PrimeTrailer

22 Configuring Filters for Reuse  Filters are designed to be reusable components  Same implementation class can be used for different filters  Different filter-name element  Possibly different init-param element  Container instantiates an instance of the class for each element public class AuditFilter implements Filter { private int mode = 0; public void init(FilterConfig arg0) throws ServletException { String modeStr = arg0.getInitParameter("mode"); if (modeStr.equals("FULL")) { mode = FULL; }... }... mode FULL

23 Example of Configuring Filter Reuse WelcomeTrailer com.ibm.filters.Trailer msg Watch for our new Web Site! DatabaseTrailer com.ibm.filters.Trailer msg Sorry, but the database is currently down.

24 Filters with RequestDispatcher  Ability to configure filters that are invoked under RequestDispatcher with forward() and include() calls Request Filters Forward / Include Filters Web Resource Filters Response Request Response Servlet v2.4 Servlet v2.3 Web Resource Forward / Include

25 Dispatcher Element  New element in the Deployment Descriptor:  REQUEST  filter if request is directly from a client  FORWARD  filter if request is from RequestDispatcher.forward() method  INCLUDE  filter if request is from RequestDispatcher.include() method  ERROR  filter if request is due to error redirection mechanism  REQUEST is the default when no element Customer Filter /customers/* FORWARD REQUEST Account Filter CustomerServlet INCLUDE

26 Filter Code Examples  Example Filters:  Logger: A simple filter that performs elapsed execution time logging for a servlet  FormChecker: A filter to check form syntax; blocks execution of the chain if form is not correct  Trailer: A filter that appends a message to the end of Web resource’s response page; uses a custom response object

27 Logger Filter: Function Description  A simple logging filter  Calculates servlet’s execution time in milliseconds  Displays the time in the server’s event log

28 Logger Filter: Deployment Descriptor Logger com.ibm.filters.Logger

29 Logger Filter: init() and destroy() Methods package com.ibm.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class Logger implements Filter { FilterConfig config; public void init(FilterConfig arg0) throws ServletException { config = arg0; } public void destroy() { }

30 Logger Filter: doFilter() Method public void doFilter (ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws ServletException, IOException { long before = System.currentTimeMillis(); arg2.doFilter(arg0, arg1); long duration = System.currentTimeMillis()- before; String msg = “Servlet duration: " + duration + “milliseconds"; config.getServletContext().log(msg); }

31 Logger Filter: How It Works  Gets timestamp from system  Uses the doFilter() method of FilterChain object to invoke next filter  Upon return from doFilter(), calculates duration  Composes message with duration  Uses the config object (FilterConfig) to get the servlet context  Uses the ServletContext.log() method to write message to the servlet’s event log

32 FormChecker Filter: Function Description  Checks that specified fields in a form have non-empty values  Filters a servlet that is the Action URL for a FORM tag  Field names are entered as the filter’s init-param names  Example: firstname  Field labels are entered as the filter’s init-param values  Example: First Name  Parameter name __FORM_NAME is reserved  Value is the name of the form (for example, Order Entry Form)  If one or more errors is found, the filter forwards the list of missing fields to a JSP page that lists the form’s name and the form fields that are missing or have empty values

33 FormChecker Filter: Deployment Descriptor FormChecker com.ibm.filters.FormChecker __FORM_NAME Prime Finder num Number FormChecker Prime

34 FormChecker Filter: init() and destroy() Methods package com.ibm.filters; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class FormChecker implements Filter { FilterConfig config; public void init(FilterConfig arg0) throws ServletException { config = arg0; } public void destroy() { }

35 FormChecker: doFilter() Method (1 of 2) public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { boolean doChain = true; ArrayList fieldList = new ArrayList(); Enumeration mandatory = config.getInitParameterNames(); if (mandatory != null) { while (mandatory.hasMoreElements()) { String parmName = (String) mandatory.nextElement(); if (!parmName.equals("__FORM_NAME")) { String parmValue = arg0.getParameter(parmName); String fieldName = ""; if (parmValue == null || parmValue.length() == 0) { doChain = false; fieldName = config.getInitParameter(parmName); fieldList.add(fieldName); }

36 FormChecker Filter: doFilter() Method (2 of 2) if (doChain) { arg2.doFilter(arg0, arg1); } else { String formNameValue = config.getInitParameter("__FORM_NAME"); String formName = (formNameValue == null) ? "Form" : formNameValue; arg0.setAttribute("formname", formName); arg0.setAttribute("fieldlist", fieldList); config.getServletContext().getRequestDispatcher ("/BadForm.jsp").forward(arg0, arg1); }

37 FormChecker Filter: How It Works  Mandatory field names are read from the filter’s init-param values as an Enumeration  Each init-param is tested to see if the request parameter of that name exists and is non-empty  If the parameter does not exist or is empty, then the field name (value of the init-param) is added to a list and the doChain flag is set to false (blocking the request)  If all mandatory fields are non-empty, doFilter() passes control to the next filter on the chain, and ultimately to the Prime servlet  Otherwise, the chain is blocked  The array list of missing field names and the form name (value of __FORM_NAME init-param) are put into request attributes  Control is forwarded to a JSP file to construct an error page

38 Wrapping Request and Response Objects  Filters may wrap the request and response objects to create new custom request and response objects  The wrapped objects might:  Override existing methods  Create new methods  Custom request and response objects are typically created by extending :  HttpServletRequestWrapper  HttpServletResponseWrapper  Subsequent methods in the filter chain have access to these new custom objects created by wrapping

39 Trailer Filter: Function Description  Appends a message to the end of the response object  The message is stored as a filter init-param  A custom response object is created:  Extends HttpServletResponseWrapper  Buffers response in a StringWriter  Overrides:  toString() : extracts StringWriter buffer as a String  getWriter(): returns PrintWriter based on the StringWriter  Subsequent filters use the custom getWriter() method  The custom response object is passed to the chain instead of the original response object  After return from the chain, the response is unwrapped, the message is added to it, and both are written to the original response object

40 Trailer Filter: Deployment Descriptor WelcomeTrailer com.ibm.filters.Trailer msg Watch for our new Web Site coming soon! WelcomeTrailer /Welcome.jsp

41 Trailer Filter: init() Method package ibm.com.filters; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class Trailer implements Filter { private String msg = ""; private FilterConfig config; public void init(FilterConfig arg0) throws ServletException { config = arg0; msg = config.getInitParameter("msg"); }

42 Trailer Filter: doFilter() Method public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { StringResponse strResp = new StringResponse((HttpServletResponse) arg1); arg2.doFilter(arg0, strResp); PrintWriter out = arg1.getWriter(); String responseString = strResp.toString(); int endBodyIndex = responseString.indexOf(" "); if (endBodyIndex > -1) { StringBuffer finalResponse = new StringBuffer(responseString.substring(0, endBodyIndex - 1)); finalResponse.append(" "); finalResponse.append(msg); finalResponse.append(" "); String finalResponseString = finalResponse.toString(); out.write(finalResponseString); } else { out.write(responseString); } out.close(); }

43 Custom Response: StringResponse package ibm.com.sw284.filters; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; public class StringResponse extends HttpServletResponseWrapper { private StringWriter responseWriterBuffer; public StringResponse(HttpServletResponse resp) { super(resp); responseWriterBuffer = new StringWriter(); } public String toString() { return responseWriterBuffer.toString(); } public PrintWriter getWriter() { return new PrintWriter(responseWriterBuffer); }

44 Trailer Filter: How It Works  New instance of custom response object (StringResponse) created  Wrapped response passed to next filter (Welcome.jsp) via chain.doFilter()  The toString() method of the StringResponse object extracts the response created by Welcome.jsp  The tag is searched for in the extracted response  Assuming the tag is found:  A substring of the response up to the tag is created  The message is added to the substring  New and tags are added  The new response is sent to the original request’s PrintWriter  Otherwise, an unmodified response is sent to the PrintWriter

45 Checkpoint 1.What interface is implemented to build a filter? 2.What object defines the sequence of filter execution? 3.How can a filter change the flow of processing to other filters? 4.What is the position of the user-requested Web resource on the filter chain? 5.How many instances of a filter does the web container create?

46 Checkpoint solutions 1.The javax.servlet.Filter interface is implemented to build a filter. 2.The FilterChain object defines the sequence of filter execution. The container passes an object of this type to the first filter. The execution is defined by the filter-mapping elements in the deployment descriptor. The order of execution is determined by the order of matching filter- mapping elements in the deployment descriptor. 3.A filter can control the flow of processing by not calling the FilterChain.doFilter() method. In this case, it is responsible for providing the response object. 4.The requested Web resource is last on the filter chain. 5.The container produces one instance of a filter for each filter element defined in the deployment descriptor.

47 Having completed this unit, you should be able to:  Describe the processing flow for filters  List the Servlet API interfaces and support object used to implement filters  Create a new filter using Rational Application Developer  Create deployment descriptor entries for a filter  Develop a basic filter using the appropriate interfaces  Develop a filter that blocks normal filter chain execution  Develop a filter using a wrapped custom response object Having completed this unit, you should be able to:  Describe the processing flow for filters  List the Servlet API interfaces and support object used to implement filters  Create a new filter using Rational Application Developer  Create deployment descriptor entries for a filter  Develop a basic filter using the appropriate interfaces  Develop a filter that blocks normal filter chain execution  Develop a filter using a wrapped custom response object Unit summary