Java Technologies Web Filters

Similar documents
SERVLET AND JSP FILTERS

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

文字エンコーディングフィルタ 1. 更新履歴 2003/07/07 新規作成(第 0.1 版) 版 数 第 0.1 版 ページ番号 1

JSP. Common patterns

Development of the Security Framework based on OWASP ESAPI for JSF2.0

COURSE 9 DESIGN PATTERNS

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

SERVLETS INTERVIEW QUESTIONS

Unit-4: Servlet Sessions:

JAVA SERVLET. Server-side Programming INTRODUCTION

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

Questions and Answers

Java Servlets. Preparing your System

Advanced Web Technology

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

Session 9. Introduction to Servlets. Lecture Objectives

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Introduction to JSP and Servlets Training 5-days

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

Servlet Basics. Agenda

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

SSC - Web applications and development Introduction and Java Servlet (I)

********************************************************************

AJP. CHAPTER 5: SERVLET -20 marks

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Servlet Fudamentals. Celsina Bignoli

Oracle 1Z Java EE 6 Web Component Developer(R) Certified Expert.

Servlets and JSP (Java Server Pages)

Session 8. Introduction to Servlets. Semester Project

26/06/56. Java Technology, Faculty of Computer Engineering, KMITL 1

Question 1. (2 points) What is the difference between a stream and a file?

Web Technology Programming Web Applications with Servlets

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

UNIT-V. Web Servers: Tomcat Server Installation:

The artist formerly known as JBoss AS. Harald ~

CIS 455 / 555: Internet and Web Systems

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

HTTP status codes. Setting status of an HTTPServletResponse

Advanced Internet Technology Lab # 4 Servlets

Servlets Basic Operations

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

The Servlet Life Cycle

Oracle EXAM - 1Z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Buy Full Product

Object-Oriented Design. March 2005 Object Oriented Design 1

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

JavaServer Pages (JSP)

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

Introduction to Servlets. After which you will doget it

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Fault tolerance made easy A head-start to resilient software design

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Lab session Google Application Engine - GAE. Navid Nikaein

Web based Applications, Tomcat and Servlets - Lab 3 -

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

CS 251 Intermediate Programming Java I/O Streams

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

Module 3 Web Component

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Input from Files. Buffered Reader

Servlets. An extension of a web server runs inside a servlet container

Table of Contents. Introduction... xxi

Using Java servlets to generate dynamic WAP content

More on Objects in JAVA TM

ServletConfig Interface

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Chapter 17. Web-Application Development

Engineering Abstractions in Model Checking and Testing. Michael Achenbach Klaus Ostermann

Web Applilicati tion S i ecur t ity SIRT Se u c i r ty ity T a r i aining April 9th, 2009

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

Java Programming Course Overview. Duration: 35 hours. Price: $900

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

Servlet for Json or CSV (or XML) A servlet serving either Json or CSV (or XML) based on GET parameter - This version uses org.json

Reference Class Mapping and Compile Fixes for Upgrading Pentaho

Using SailFin and Eclipse to build SIP-based and RESTful applications

Backend. (Very) Simple server examples

Example: Copying the contents of a file

Java4570: Session Tracking using Cookies *

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

Discovery data feed for Eid 2.0

CSC309: Introduction to Web Programming. Lecture 10

Fast Track to Java EE 5 with Servlets, JSP & JDBC

Introduction to Web applications with Java Technology 3- Servlets

Programming overview

Java Servlets Basic Concepts and Programming

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Servlet and JSP Review

Module 4: SERVLET and JSP

PASS4TEST. IT Certification Guaranteed, The Easy Way! We offer free update service for one year

PIC 20A Streams and I/O

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

CN208 Introduction to Computer Programming

Applet. 1. init (): called once by the applet containers when an applet is loaded for execution.

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Transcription:

Java Technologies Web Filters

The Context Upon receipt of a request, various processings may be needed: Is the user authenticated? Is there a valid session in progress? Is the IP trusted, is the user's agent supported,...? When sending a response, the result may require various processings: Add some additional design elements. Trim whitespaces, etc.

Example In the login controller: User user = new User(); user.setname(request.getparameter("username")); user.setpassword(request.getparameter("userpassword")); session.setattribute("user", user); In every web component that requires a valid user: User user = (User) session.getattribute("user"); if (user == null) { response.sendredirect("login.jsp"); return; // ok, we have a user in the session //... crosscutting concern

The Concept of Filters We need a component that: Dynamically intercepts requests and responses preprocessing / postprocessing Provides reusable functionalities that can be "attached" to any kind of web resource Can be used declarative, in a plug-in manner Is (usually) independent (does not have any dependencies on other web resource for which it is acting as a filter)

Common Usages Authentication Logging and auditing Image conversion, scaling, etc. Data compression, encryption, etc. Localization Content transformations (for example, XSLT) Caching...

Intercepting Filter Design Pattern

Java EE Filter Architecture An API for creating the filters javax.servlet.filter interface A method for configuring and plugging-in the filters (mapping them to other resources) declarative (in web.xml or using @WebFilter) A mechanism for chaining the filters javax.servlet.filterchain

javax.servlet.filter interface public interface Filter() { /** * Called by the web container to indicate to a filter * that it is being placed into service. */ void init(filterconfig filterconfig); /** * The dofilter method of the Filter is 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 */ void dofilter(servletrequest request, ServletResponse response, FilterChain chain); void destroy();

Example: Logging @WebFilter(urlPatterns = {"/*") public class LogFilter implements Filter { public void dofilter(servletrequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; // Find the IP of the request String ipaddress = request.getremoteaddr(); // Write something in the log System.out.println( "IP " + ipaddress + ", Time " + new Date().toString()); chain.dofilter(req, res);

Example: Character Encoding public void init(filterconfig filterconfig) throws ServletException { //read the character encoding from a filter initialization parameter this.encoding = filterconfig.getinitparameter("encoding"); // for example: UTF-8 or ISO 8859-16 or Windows-1250 etc. public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (encoding!= null) { //useful if the browser does not send character encoding information //in the Content-Type header of an HTTP request request.setcharacterencoding(encoding); chain.dofilter(request, response);

javax.servlet.filterchain interface public interface FilterChain() { void dofilter( ServletRequest request, ServletResponse response);

Specifying Filter Mappings web.xml <filter> <filter-name>hellofilter</filter-name> <filter-class>somepackage.hellofilterimpl</filter-class> <init-param> <param-name>greeting</param-name> <param-value>hello World!</param-value> </init-param> </filter> <filter-mapping> <filter-name>hellofilter</filter-name> <url-pattern>/hello/*</url-pattern> </filter-mapping> @WebFilter( filtername = "HelloFilter", urlpatterns = {"/hello/*", initparams = { @WebInitParam(greeting = "Hello World!") ) public class HelloFilterImpl implements Filter { many-to-many

The generic structure of a filter public class GenericFilter implements Filter { public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { dobeforeprocessing(request, response); Throwable problem = null; try { chain.dofilter(request, response); catch(throwable t) { problem = t;... doafterprocessing(request, response); if (problem!= null) { processerror(problem, response);

Filtering the response The Problem: Modify the content of the response chain.dofilter( request, response) response Header getoutputstream getwriter Dynamic Content Footer

Decorator Design Pattern You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class. Decorator Design Pattern: Attach additional responsibilities to an object dynamically, without altering its structure (class signature). Wrapper

Decorator example: Java IO public interface Reader { int read(); public class FileReader implements Reader { public int read() {... public class BufferedReader implements Reader { private FileReader in; public BufferedReader(FileReader in { this.in = in; //receive the original object public int read() { return in.read(); // inherit old functionality public String readline() { // create new functionality... Reader original = new FileReader("someFile"); Reader decorated = new BufferedReader(reader);

HTTP Wrappers Decorating the request HttpServletRequestWrapper implements HttpServletRequest ServletRequestWrapper wrapper = new HttpServletRequestWrapper(req) { @Override public String getlocalname() { return "localhost"; ; chain.dofilter(wrapper, response); Decorating the response HttpServletResponseWrapper implements HttpServletResponse

Creating a Response Wrapper public class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; public CharResponseWrapper(HttpServletResponse response) { super(response); output = new CharArrayWriter(); @Override public PrintWriter getwriter(){ // Hide the original writer return new PrintWriter(output); public String tostring() { return output.tostring();

Decorating the response CharResponseWrapper wrapper = new CharResponseWrapper( (HttpServletResponse)response ); //Send the decorated object as a replacement for the original response chain.dofilter(request, wrapper); //Get the dynamically generated content from the decorator Strng content = wrapper.tostring(); // Modify the content StringWriter sw = new StringWriter(); sw.write(content.substring(...)); sw.write("<h1>thank you!</h1>"); sw.write(...); //Send the modified content using the original response PrintWriter out = response.getwriter(); out.write(sw.tostring());

Conclusions The filter mechanism provides a way to encapsulate common functionality in a component that can reused in many different contexts. Filters are easy to write and configure as well as being portable and reusable.