SERVLET AND JSP FILTERS

Similar documents
Java Technologies Web Filters

JAVA SERVLET. Server-side Programming INTRODUCTION

JSP. Common patterns

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

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

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

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

Servlet Basics. Agenda

Unit-4: Servlet Sessions:

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

Servlet Fudamentals. Celsina Bignoli

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

Advanced Internet Technology Lab # 4 Servlets

ServletConfig Interface

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

The Servlet Life Cycle

Web based Applications, Tomcat and Servlets - Lab 3 -

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

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

Session 8. Introduction to Servlets. Semester Project

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

UNIT-V. Web Servers: Tomcat Server Installation:

Session 9. Introduction to Servlets. Lecture Objectives

Advanced Web Technology

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

Questions and Answers

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

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

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

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

Servlets and JSP (Java Server Pages)

Web Technology Programming Web Applications with Servlets

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

AJP. CHAPTER 5: SERVLET -20 marks

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

COURSE 9 DESIGN PATTERNS

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

Servlet and JSP Review

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

Introduction to JSP and Servlets Training 5-days

Unit 5 JSP (Java Server Pages)

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

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

SERVLETS INTERVIEW QUESTIONS

Unit 4 - Servlet. Servlet. Advantage of Servlet

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

CSC309: Introduction to Web Programming. Lecture 10

Java Servlets Basic Concepts and Programming

A Servlet-Based Search Engine. Introduction

Introduction to Web applications with Java Technology 3- Servlets

Java Servlets. Preparing your System

COMP9321 Web Application Engineering

JavaServer Pages (JSP)

Table of Contents. Introduction... xxi

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

Servlets by Example. Joe Howse 7 June 2011

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

CS506 Web Design & Development Final Term Solved MCQs with Reference

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Module 4: SERVLET and JSP

JSP Scripting Elements

COMP9321 Web Application Engineering

WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD

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

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

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

Lab session Google Application Engine - GAE. Navid Nikaein

Web Application Services Practice Session #2

Introduction to Servlets. After which you will doget it

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Backend. (Very) Simple server examples

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty

Stateless -Session Bean

First Servlets. Chapter. Topics in This Chapter

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil

Handout 31 Web Design & Development

Handling Cookies. Agenda

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

The Structure and Components of

Connection Pools. The ConnectionObject

Using Java servlets to generate dynamic WAP content

CIS 455 / 555: Internet and Web Systems

Dynamic Struts Configuration Dipl.-Inf. Manfred Wolff January 2004

JSF Page Navigation. The first example we ll look at is available as jsf_ex2a.zip on your notes page.

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

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

CS433 Technology Overview

Java4570: Session Tracking using Cookies *

Université du Québec à Montréal

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

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

Chapter 17. Web-Application Development

Supplement IV.E: Tutorial for Tomcat For Introduction to Java Programming By Y. Daniel Liang

Getting started with Winstone. Minimal servlet container

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

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

Java E-Commerce Martin Cooke,

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

SWE642 Oct. 22, 2003

Transcription:

SERVLET AND JSP FILTERS

FILTERS OVERVIEW Filter basics Accessing the servlet context Using initialization parameters Blocking responses Modifying responses

FILTERS: OVERVIEW Associated with any number of servlets or JSP pages Examine request coming into servlets or JSP pages, then: Invoke the resource (i.e., the servlet or JSP page) in the normal manner. Invoke the resource with modified request information. Invoke the resource but modify the response before sending it to the client. Prevent the resource from being invoked and instead redirect to a different resource, return a particular status code, or generate replacement output.

ADVANTAGES OF FILTERS Encapsulate common behavior. Have 30 different servlets or JSP pages that need to compress their content to decrease download time? Make 1 compression filter and apply it to all 30 resources. Separate high-level access decisions from presentation code. Want to block access from certain sites without modifying the individual pages to which these access restrictions apply? Create an access restriction filter and apply it to as many pages as you like. Apply wholesale changes to many different resources. Have a bunch of existing resources that should remain unchanged except that the company name should be changed? Make a string replacement filter and apply it wherever appropriate.

STEPS TO CREATING FILTERS 1. Create class that implements Filter interface. Methods: dofilter, init, destroy 2. Put filtering behavior in dofilter. Args: ServletRequest, ServletResponse, FilterChain 3. Call dofilter method of the FilterChain. This invokes next filter (if any) or actual resource 4. Register the filter with the appropriate servlets and JSP pages. Use filter and filter-mapping in web.xml. 5. Disable invoker servlet.

THE DOFILTER METHOD Basic format public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { chain.dofilter(request,response); } Note on first two arguments They are of type ServletRequest and ServletResponse, not HttpServletRequest and HttpServletResponse. Do a typecast if you need HTTP-specific capabilities Note on final argument It is a FilterChain, not a Filter. Its dofilter method is different two arguments only.

A SIMPLE REPORTING FILTER public class ReportFilter implements Filter { public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; System.out.println(req.getRemoteHost() + " tried to access " + req.getrequesturl() + " on "+new Date() + "."); chain.dofilter(request,response); }

A SIMPLE REPORTING FILTER (CONTINUED) public void init(filterconfig config) throws ServletException { } public void destroy() { } }

DECLARING THE REPORTING FILTER <web-app > <!-- Register the name "Reporter" for ReportFilter. --> <filter> <filter-name>reporter</filter-name> <filter-class> coreservlets.filters.reportfilter </filter-class> </filter> </web-app> Important note Servers load filters into memory when the Web app first comes up. So, if that filter is not found, your entire Web app is disabled.

ASSOCIATING REPORTING FILTER WITH GIVEN URLS <!-- Apply Reporter filter to home page. --> <filter-mapping> <filter-name>reporter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping> <!-- Also apply Reporter filter to servlet named "TodaysSpecial". --> <filter-mapping> <filter-name>reporter</filter-name> <servlet-name>todaysspecial</servlet-name> </filter-mapping> </web-app>

REPORTING FILTER (CONTINUED) Point: A single filter can apply to lots of different resources in transparent manner The individual resources do not need any special code Example of Reporting filter

ACCESSING THE SERVLET CONTEXT What if filter wants to read or write Web application-wide parameters? Or it simply wants to log data? You can use methods in ServletContext for this Surprisingly, the dofilter method provides no access to the ServletContext Neither ServletRequest nor ServletResponse provides access to it either Solution: store the ServletContext in init Call getservletcontext on the FilterConfig argument that is passed to init paramter Store the result in an instance variable (field) of the filter Access the field from the dofilter method

A LOGGING FILTER public class LogFilter implements Filter { { protected FilterConfig config; private ServletContext context; private String filtername; public void init(filterconfig config) throws ServletException // In case it is needed by subclass. } this.config = config; context = config.getservletcontext(); filtername = config.getfiltername();

A LOGGING FILTER (CONTINUED) public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; context.log (req.getremotehost() + " tried to access " + req.getrequesturl() + " on " + new Date() + ". " + "(Reported by " + filtername + ".)"); chain.dofilter(request,response); }

APPLYING LOGGING FILTER TO ENTIRE WEB APPLICATION <web-app> <filter> <filter-name>logger</filter-name> <filter-class> coreservlets.filters.logfilter </filter-class> </filter> <filter-mapping> <filter-name>logger</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

LOGGING FILTER: RESULTS Log file: On Tomcat, the log file is located in the tomcat_dir/logs directory. audits.irs.gov tried to access http://www.filtersrus.com/filters/business-plan.jsp on Tue Apr 2 15:16:15 EDT 2012. (Reported by Logger.) ceo.enron.com tried to access http://www.filtersrus.com/filters/tax-shelter/ on Wed Apr 3 10:24:11 EDT 2012. (Reported by Logger.)

LogFilter prints an entry in the log file every time the associated servlet or JSP page is accessed. Suppose you want to modify it so that it only notes accesses that occurs at unusal times. Because unusual is situation dependent,the servlet should provide default values for the abnormal time ranges and let deployers override these values by supplying initialization parameters.

USING FILTER INITIALIZATION PARAMETERS Deployers. This third group is the one served by initialization parameters. Members of this group are people who take existing Web applications (or individual servlets or JSP pages) and deploy them in a customized environment. Resources with initialization parameters Servlets, JSP pages, servlet context, filters, listeners.

DECLARING FILTER INITIALIZATION PARAMETERS <filter> <filter-name>lateaccessfilter</filter-name> <filter-class> coreservlets.filters.lateaccessfilter </filter-class> <init-param> <param-name>starttime</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>endtime</param-name> <param-value>10</param-value> </init-param> </filter>

READING INIT PARAMS: AN ACCESS TIME FILTER { public void init(filterconfig config) throws ServletException context = config.getservletcontext(); formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); try { starttime = Integer.parseInt(config.getInitParameter("startTime")); endtime = Integer.parseInt(config.getInitParameter("endTime")); } { } } catch(numberformatexception nfe) starttime = 22; // 10:00 p.m. endtime = 6; // 6:00 a.m.

AN ACCESS TIME FILTER (CONTINUED) public void dofilter(servletrequest request, ServletResponse response,filterchain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; GregorianCalendar calendar = new GregorianCalendar(); int currenttime = calendar.get(calendar.hour_of_day); if (isunusualtime(currenttime,starttime,endtime)) { context.log("warning: " + req.getremotehost() + " accessed " + req.getrequesturl() + on " + formatter.format(calendar.gettime())); } chain.dofilter(request,response); }

BLOCKING THE RESPONSE Idea Normal situation: call dofilter on FilterChain object Unusual situation: redirect response or generate custom output Generic Example public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req =(HttpServletRequest)request; HttpServletResponse res =(HttpServletResponse)response; if (isunusualcondition(req)) { } else { } } res.sendredirect("http://www.somesite.com"); chain.dofilter(req,res);

A BANNED SITE FILTER public class BannedAccessFilter implements Filter { private HashSet<String> bannedsitetable; public void init(filterconfig config) throws ServletException { bannedsitetable = new HashSet<String>(); String bannedsites =config.getinitparameter("bannedsites"); StringTokenizer tok =new StringTokenizer(bannedSites); while(tok.hasmoretokens()) { } } String bannedsite = tok.nexttoken(); bannedsitetable.add(bannedsite); System.out.println("Banned " + bannedsite); public void destroy() {}

CONTINUE. { { public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException HttpServletRequest req = (HttpServletRequest)request; String requestinghost = req.getremotehost(); String referringhost=getreferringhost(req.getheader("referer")); String bannedsite = null; boolean isbanned = false; if (bannedsitetable.contains(requestinghost)) bannedsite = requestinghost; isbanned = true; } { } else if (bannedsitetable.contains(referringhost)) bannedsite = referringhost; isbanned = true; if (isbanned) { showwarning(response, bannedsite);// Custom response } else { chain.dofilter(request,response); }}

CONTINUE private String getreferringhost (String refererringurlstring) { try { URL referringurl = new URL(refererringURLString); return(referringurl.gethost()); } { } } catch(malformedurlexception mue) return(null);

CONTINUE private void showwarning(servletresponse response, String bannedsite) throws ServletException, IOException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println ("<HTML>\n" + "<HEAD><TITLE>Access Prohibited</TITLE></HEAD>\n"+ "<BODY BGCOLOR=\"WHITE\">\n" + "<H1>Access Prohibited</H1>\n" + "Sorry, access from or via " + bannedsite + "\n"+ "is not allowed.\n" + "</BODY></HTML>"); }

REGISTERING THE BANNED SITE FILTER IN WEB.XML <web-app> <filter> <filter-name>bannedaccessfilter</filter-name> <filter-class> coreservlets.filters.bannedaccessfilter </filter-class> <init-param> <param-name>bannedsites</param-name> <param-value> www.tbiq.com www.bettersite.com www.coreservlets.com </param-value> </init-param> </filter>

CONTINUE <filter-mapping> <filter-name>bannedaccessfilter</filter-name> <url-pattern>/todays-special</url-pattern> </filter-mapping> <servlet> <servlet-name>todaysspecial</servlet-name> <servlet-class> coreservlets.todaysspecialservlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>todaysspecial</servlet-name> <url-pattern>/todays-special</url-pattern> </servlet-mapping> </web-app>

FILTER IN ACTION Direct Access : http://localhost:8080/filters/todays-special Access via a link from a page at www.coreservlet.com http://localhost:8080/filters/todays-special Example : http://localhost:8080/filters/linker.html http://www.tbiq.com/linker.html

ADVANCED FILTERS:MODIFYING THE RESPONSE 1. Create a response wrapper. Extend HttpServletResponseWrapper. 2. Provide a PrintWriter that buffers output. Override getwriter method to return a PrintWriter that saves everything sent to it and stores that result in a field 3. Pass that wrapper to dofilter. This call is legal because HttpServletResponseWrapper implements HttpServletResponse. 4. Extract and modify the output. After call to dofilter method of the FilterChain, output of the original resource is available to you through whatever mechanism you provided in Step 2. Modify or replace it as appropriate. 5. Send the modified output to the client. Original resource no longer sends output to client (output is stored in your response wrapper instead). You have to send the output. So, filter needs to obtain the PrintWriter or OutputStream from original response object and pass modified output to that stream.

FOR EXAMPLE Servlet file : import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.getwriter().println("test"); } }

CLASS THAT EXTENDS HTTPSERVLETRESPONSEWRAPPER public class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; public String tostring() { return output.tostring(); } public CharResponseWrapper(HttpServletResponse response) { } { super(response); output = new CharArrayWriter(); public PrintWriter getwriter() return new PrintWriter(output); }

CREATE A FILTER public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { } System.out.println("BEFORE filter"); PrintWriter out = response.getwriter(); CharResponseWrapper responsewrapper = new CharResponseWrapper((HttpServletResponse)response); chain.dofilter(request, responsewrapper); String servletresponse = new String(responseWrapper.toString()); out.write(servletresponse + " filtered"); // Here you can change the response System.out.println("AFTER filter, original response: " + servletresponse);

ANOTHER EXAMPLE IS A COMPRESSION FILTER http://www.java2s.com/code/java/servlets/compressi onfilter.htm

CONFIGURING FILTERS TO WORK WITH REQUESTDISPATCHER Version 2.3 of the servlet specification only allowed us to configure filters for requests that came directly from the client. Filters did not apply to requests that were made as a result of the forward or include methods of RequestDispatcher. Version 2.4 introduced a new deployment descriptor element, dispatcher, which allows us to configure filters to do just that. The optional dispatcher element must be placed inside the filter-mapping element after the url-pattern or servlet-name element.

CONTINUE It can be assigned one of the following values: REQUEST, FORWARD, INCLUDE, or ERROR. If you want to apply the filter to different types of requests, you can do so by repeating the dispatcher element with a different value. Here is a simple example: <filter-mapping> <filter-name>myfilter</filter-name> <url-pattern>/index.jsp</url-pattern> <dispatcher>request</dispatcher> <dispatcher>include</dispatcher> </filter-mapping>

REQUEST: When the dispatcher element is assigned REQUEST, the filter mapping will apply to any request coming directly from the client for the Web resources matching the url-pattern or servlet-name element. If the resource specified by the filter-mapping element is invoked using methods of RequestDispatcher (i.e., forward or include), the filter mapping will not apply and the associated filter will not be invoked. If the dispatcher element is omitted, the server assumes the REQUEST setting and configures the filter mapping accordingly. However, if any other setting is specified (e.g., INCLUDE), the filter mapping will not automatically apply to requests coming directly from the client. In such situations, you must specify an additional dispatcher element with the value of REQUEST if you want to intercept direct client requests as well.

FORWARD AND INCLUDE FORWARD : When the dispatcher element is assigned FORWARD, the filter mapping will apply to any request made as a result of the RequestDispatcher.forward method call to the Web resources matching the url-pattern or servletname element. INCLUDE : When the dispatcher element is assigned INCLUDE, the filter mapping will apply to any request made as a result of the RequestDispatcher.include method call to the Web resources matching the url-pattern or servletname element.

ERROR When the dispatcher element is assigned ERROR, the filter mapping will apply to any request that was forwarded by the server to the Web resource matching the url-pattern or servlet-name element using the error page mechanism. For example, suppose the NotFound.jsp error page was designated in web.xml to serve as an HTTP 404 custom error page as follows: <error-page> <error-code>404</error-code> <location>/notfound.jsp</location> </error-page>

CONTINUE Now, suppose we specify a filter-mapping element as follows: <filter-mapping> <filter-name>somefilter</filter-name> <url-pattern>/notfound.jsp</url-pattern> <dispatcher>error</dispatcher> <filter-mapping> The server will forward any request to a nonexisting resource to NotFound.jsp as part of the error page mechanism. Because we specified SomeFilter to intercept a request to NotFound.jsp when the request is being made as part of the error page mechanism, SomeFilter will be invoked before the request reaches NotFound.jsp.

SUMMARY Implement the Filter interface Override dofilter, init, and destroy init and destroy are often empty Declare filter in web.xml Give it a name and designate URLs to which it applies Accessing the servlet context Look it up in init, store it in a field Filters have init parameters Blocking resources Simply omit call to FilterChain.doFilter Modifying response Pass a wrapper to resource, invoke resource, extract output from wrapper, modify it, pass it to client. Configuring Filters to Work with RequestDispatcher just include <dispatcher> element to<filter-mapping>

THANK YOU