• Nu S-Au Găsit Rezultate

– Is the user authenticated?


Academic year: 2022

Share "– Is the user authenticated?"


Text complet


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.



In the login controller:

User user = new User();



session.setAttribute("user", user);

In every web component that requires a valid user:

User user = (User) session.getAttribute("user");

if (user == null) {




// ok, we have a user in the session // ...




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


Logging and auditing

Image conversion, scaling, etc.

Data compression, encryption, etc.


Content transformations (for example, XSLT)




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



chain.doFilter(request, response);


You may want to read: “The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)” by Joel Spolsky


javax.servlet. FilterChain interface

public interface FilterChain() { void doFilter(

ServletRequest request, ServletResponse response);



Specifying Filter Mappings







<param-value>Hello World!</param-value>








filterName = "HelloFilter", urlPatterns = {"/hello/*"}, initParams = {

@WebInitParam(greeting = "Hello World!")}


public class HelloFilterImpl implements Filter { …




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);

} } ...



Example: Count and Measure

@WebFilter(urlPatterns = {"/someComponent"})

public class ResponeTimeFilter implements Filter {

private AtomicInteger counter = new AtomicInteger();

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

throws IOException, ServletException { // Count the requests

int n = counter.addAndGet(1);

// Start the timer

long t0 = System.currentTimeMillis();

chain.doFilter(req, res);

// Stop the timer

long t1 = System.currentTimeMillis();

app.log("Request " + n + " took " + (t1 – t0) + "ms");

} }



Filtering the response

The Problem:

Modify the content of the response

– chain.doFilter(

request, response)

– response



Dynamic Content



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


Decorator Design Pattern: Attach additional

responsibilities to an object dynamically, without altering its structure (class signature).



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


implements HttpServletRequest

ServletRequestWrapper wrapper = new HttpServletRequestWrapper(req) { @Override

public String getLocalName() { return "localhost";

} };

chain.doFilter(wrapper, response);

Decorating the response


implements HttpServletResponse


Creating a Response Wrapper

public class SimpleResponseWrapper

extends HttpServletResponseWrapper {

private final StringWriter output;

public SimpleResponseWrapper(HttpServletResponse response) { super(response);

output = new StringWriter();



public PrintWriter getWriter() { // Hide the original writer

return new PrintWriter(output);



public String toString() { return output.toString();




Decorating the response

@WebFilter(filterName = "ResponseDecorator", urlPatterns = {"/*"}) public class ResponseDecorator implements Filter {


public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

SimpleResponseWrapper wrapper

= new SimpleResponseWrapper((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 String content = wrapper.toString();

// Modify the content

content += "<p> Mulțumim!";

//Send the modified content using the original response PrintWriter out = response.getWriter();


} ...




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.



public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {.

However, the sphere is topologically different from the donut, and from the flat (Euclidean) space.. Classification of two

• a dedicated thread executes a particular request and does not return to thread pool until it completes the execution and returns a response;... Node.js

In the rest of this section, given a role named R, we denote with R its entire HLPSL definition which includes the roles signature (the name, R, and the parameters, that we denote

● When a component is bound to a managed bean, the application has two views of the component's data:. – The model view, in which data is represented as data types, such as

To do so we calculate the best placement of the modules on the network compute servers, given user profile and con- text conditions informations such as: typical user request,

Polytechnica University of Bucharest The Polytechnica University of Bucharest (UPB) is, with more than 190 years of existence, one of the fundamental and

This philosophy, called user-centered design, incorporates user concerns and advocacy from the beginning of the design process and dictates.. the needs of the user should be foremost