0% found this document useful (0 votes)
10 views60 pages

Slot 3 - 4 - Filter and Annotation

dsfdsfsdfsd

Uploaded by

Phuc Vinh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views60 pages

Slot 3 - 4 - Filter and Annotation

dsfdsfsdfsd

Uploaded by

Phuc Vinh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

ĐẠI HỌC FPT CẦN THƠ

Filter and Annotation


Objective

Explain the concept and working of filters

List the benefits of filters

Explain the Filter API interfaces and there methods

Explain the use of wrapper classes in managing Servlets

Explain how to alter a request and response using filters

Filter and Annotation_Lương Hoàng Hướng 2


Objective

Describe the basic concept of annotations

Explain the different types of annotations supported in Servlet

API

Explain the steps to upload the file using HTML form elements

Explain the mechanism to upload files on the server using Servlet

Filter and Annotation_Lương Hoàng Hướng 3


Introduction
❖ Java supports filter objects which performs processing of the request before it
acquires the resource.
❑ For example, data sent in the response from a Servlet must be encrypted to avoid any
malfunction threat.
❑ This needs an extra processing of encryption to be done on the received response from the
Servlet.
❖ Before sending the response, filters perform manipulation of the responses
sent to the client.
❖ Figure shows the processing of request and response done by filters.

Filter and Annotation_Lương Hoàng Hướng 4


Concept of Filter

❖ Filters:
❑ Are Java classes.
❑ Used to encapsulate the preprocessing and post processing functionalities common to a
group of Servlets or JSP pages.
❑ Were introduced as a Web component in Java Servlet specification.
❑ Reside in the Web container along with the other Web components, such as Servlet or JSP
pages.
❖ Figure depicts filters in a Web application.

Filter and Annotation_Lương Hoàng Hướng 5


Concept of Filter

❖ Some of the important features provided by the filters to the Web


applications are as follows:

Optimization of the time taken to send a response back to a client.

Compression of the content size sent from a Web server to a user over the
Internet.

Conversion of images, texts, and videos to the required format.

Optimization of the available bandwidth on the network.

Authentication of the users in the secured Web site.

Encryption of the request and response header for addressing security concerns.

Filter and Annotation_Lương Hoàng Hướng 6


Filter Channing

❖ There can be more than one filter between the client and the Web resources,
thus forming a filter chain.
❖ Figure shows channing of the filters.

❑ A request or a response is passed through one filter to the next in the filter chain.
❑ Each request and response is serviced by filters configured in the chain, before the
Servlet is called by the Web container and after the Servlet responds.

Filter and Annotation_Lương Hoàng Hướng 7


Working of Filter

❖ A typical filter operates in the following way:

The Web container instantiates the filters and loads them for preprocessing.

The filter intercepts the request from the user to the servlet.

After the request is processed, the filter can do the following:

• Generate response and return to the client.


• Pass the modified or unmodified request to other filter in the chain.
• If the request is received by the last filter in the chain, it passes the request to the
destination Servlet.
• It may route the request to a different resource rather than the associated Servlet.

Then, the filter sends the serviced request to the appropriate Servlet.

Filter and Annotation_Lương Hoàng Hướng 8


Working of Filter

❖ When the response is returned to the client, the response passes through
same set of filters in reverse order.
❖ Figure depicts working of a typical filter.

Filter and Annotation_Lương Hoàng Hướng 9


Usage of Filters
❖ Some of the filter categories are as follows:

Authentication
filters Allows the users to access any resource in secured Websites after
providing proper username and password.

Logging and auditing


filters
Tracks the activities of users on a Web application and log them.

Image conversion
filters
Scales the image size or change the image type as per requirements.

Data compression
filters Helps in compressing uploaded or downloaded file size, thereby
reducing the bandwidth requirement and time for downloading.

Encryption filters
Helps in encrypting the request and response header.

Filter and Annotation_Lương Hoàng Hướng 10


Usage of Filters

Helps in registering the particular database for a Web application


Filters that trigger before they retrieve or manipulate data according to the request made
resource access events by the client.

XML transformation Reads the XML data from the response and applies an XSLT
filters transformation before sending it to the client browser.

❖ Figure depicts a compression filter.

Filter and Annotation_Lương Hoàng Hướng 11


Filter API
❖ It brings in all the required interfaces namely Filter, FilterChain, and
FilterConfig for creating a filter class into the javax.servlet package.
❖ Figure depicts hierarchy structure of Filter API.

Filter and Annotation_Lương Hoàng Hướng 12


Filter Interface

❖ The Filter interface is part of the Servlet API.


❖ The Filter interface provides the life cycle methods of a filter. It must be
implemented to create a filter class.
❖ The methods of the Filter interface are as follows:
❑ init()

 It is called by the servlet container to initialize the filter.


 It is called only once.
 The init() method must complete successfully before the filter is asked to
do any filtering work.
 Syntax:
public void init(FilterConfig filterConfig)

throws ServletException

Filter and Annotation_Lương Hoàng Hướng 13


Filter Interface
❑ doFilter()
 It is called by the container each time a request or response is processed.
 It then examines the request or response headers and customizes them as per
the requirements.
 It also passes the request or response through the FilterChain object to
the next entity in the chain.
 Syntax:
public void doFilter(ServletRequest req,
ServletResponse res, FilterChain chain) throws
IOException, ServletException
❑ destroy()
 It is called by the servlet container to inform the filter that its service is no
more required.
 It is called only once.
 Syntax:
public void destroy()

Filter and Annotation_Lương Hoàng Hướng 14


Filter Interface

❖ Figure shows the template of a class implementing the Filter interface.

Filter and Annotation_Lương Hoàng Hướng 15


Filter Interface
❖ The code snippet demonstrates the implementation of filter to display a
message before the invocation of the configured Servlet.

Filter and Annotation_Lương Hoàng Hướng 16


Configuring Filter
❖ The configuration of a filter inside the web.xml file ensures that filter is the
part of that application.
❖ In the deployment descriptor, filter is declared by the <filter> element.
❖ It defines a filter class and its initialization parameters.
❖ Following elements can be defined within a filter element:
❑ <display-name>

❑ <description>

❑ <filter-name>

❑ <filter-class>

❑ <init-param>

Filter and Annotation_Lương Hoàng Hướng 17


Filter-mapping Element
❖ It specifies which filter to execute depending on a URL pattern or a Servlet name.
❖ This actually sets up a logical relation between the filter and the Web application
for sequential control flow of request and response between them.
❖ Following elements are defined inside a filter-mapping element:

• The element inside the deployment descriptor holds the name of the
<filter
filter to which a URL pattern or a Servlet is mapped.
-name> • It is a mandatory element for mapping a filter.

• The element describes a pattern used to resolve URLs.


<url-
pattern • It is a mandatory element for mapping a filter.
>

• The element specifies the name of a servlet whose request and


response will be modified by the filter.
<servle
t-name> • It is a mandatory element.

Filter and Annotation_Lương Hoàng Hướng 18


Filter-mapping Element
❖ The code snippet shows the mapping of MessageFilter with the
MyServlet in the web.xml file.

Filter and Annotation_Lương Hoàng Hướng 19


Passing Initialization Parameters to
Filter
❖ The init() method of a filter initializes the filter.
❖ It receives the object of FilterConfig object created by the Web container.
❖ Then, the initialization parameters are read in the init() using the methods
of FilterConfig.
❖ Table lists some of the methods of FilterConfig.
Method Description

String getFilterName() Returns the name of the filter defined in the web.xml or
deployment descriptor file in the Web application.

String Returns the value of the named initialization parameter as


getInitParameter(String name) a string.
Returns null if the servlet has no attribute.
Enumeration Returns the names of the initialization parameter as an
getInitParameterNames() enumeration of String objects.

S e r v l e t C o n t e x t Returns the ServletContext object used by the caller to


getServletContext() interact with its Servlet container and filter.

Filter and Annotation_Lương Hoàng Hướng 20


Passing Initialization Parameters to
Filter
❖ The code snippet exhibits the use of the methods in the FilterConfig interface.

Filter and Annotation_Lương Hoàng Hướng 21


Passing Initialization Parameters to
Filter
❖ Figure shows the configuration of filter with initialization parameters in the
web.xml file.

Filter and Annotation_Lương Hoàng Hướng 22


Use of Wildcard in Mapping
❖ The <url-element> element in the deployment descriptor is used to
specify URL pattern for the Web resources.
❖ It can either contain a specific URL or a even wild card character (*) can be
used to match a set of URLs.
❖ All the URLs mapped with filters are applied before the Servlet are invoked.
❖ When a Web application is executed, it creates an instance of each filter that
has been declared in the deployment descriptor.
❖ The sequence for execution of these filters is in the order, as they are declared
in the deployment descriptor.

Filter and Annotation_Lương Hoàng Hướng 23


Use of Wildcard in Mapping
❖ The code snippet shows how to include multiple filters with a request to a mapped
Servlet.

❖ The code snippet shows the mapping for multiple patterns with the filter.

Filter and Annotation_Lương Hoàng Hướng 24


Manipulating Requests and Responses
❖ The filters can wrap the request or response objects in custom wrappers.
❖ The wrapper classes:
❑ Helps to intercept the request or response, before they can reach their logical
destination.
❑ Create the object to capture the request and response, before they reach server
and client respectively.
❖ Figure shows the working of wrapper objects used for processing of request
and response in Servlets.

Filter and Annotation_Lương Hoàng Hướng 25


Manipulating Requests and Responses

❖ The classes defined by Servlet API for wrapping request and response are as
follows:
❑ ServletRequestWrapper

 This class provides a convenient implementation of the


ServletRequest interface.
❑ ServletResponseWrapper

 This class provides a convenient implementation of the

ServletResponse interface.

Filter and Annotation_Lương Hoàng Hướng 26


Manipulating Requests and Responses
❖ The code snippet shows how to extend HttpServletRequestWrapper
class.

Filter and Annotation_Lương Hoàng Hướng 27


Manipulating Requests and Responses
❖ The code snippet shows how to extend HttpServletResponseWrapper
class.

Filter and Annotation_Lương Hoàng Hướng 28


Introduction to Annotation
❖ Annotations are one of the major advancement from Java EE 5.0 that are used
to configure the server components.
❖ Using annotation in Java EE, makes the standard application.xml and
web.xml deployment descriptors files optional.
❖ Annotations:
❑ Can be defined as metadata information that can be attached to an element
within the code to characterize it.
❑ Simplifies the developer’s work by reducing the amount of code to be written by
moving the metadata information into the source code itself.
❑ Can be added to program elements such as classes, methods, fields, parameters,
local variables, and packages.
❑ Never executed.
❑ Is processed when the code containing it are compiled or interpreted by
compilers, deployment tools, and so on.
❑ Can result in the generation of code documents, code artifacts, and so on.

Filter and Annotation_Lương Hoàng Hướng 29


Advantages of Annotation

❖ Some of the advantages of using annotations are as follows:

Ease of Use
• Annotations are checked and compiled by the Java language compiler and
are simple to use.

Portability
• Annotations are portable.

Type Checking
• Annotations are instances of annotation types and are compiled in their own
class files.

Runtime Reflection
• Annotations are stored in the class files and accessed for runtime access.

Filter and Annotation_Lương Hoàng Hướng 30


Declaring Annotation
❖ The annotation type is used for defining an annotation and is used when
custom annotation needs to be created.
❖ An annotation type takes an ‘at (@)’ sign, followed by the interface
keyword and the annotation name.
❖ An annotation takes the form of an ‘at’ (@) sign, followed by the annotation
type.
❖ The various standard annotations include @Deprecated, @Override,
@SuppressWarnings, @Documented, and @Retention.

Filter and Annotation_Lương Hoàng Hướng 31


Declaring Annotation

❖ The rules and guidelines to be followed by a developer before using


annotation are as follows:

A field or a method can be assigned any access qualifier.

A field or method cannot be static.

The fields or methods of the main class that have been annotated for injection must
be static.

Resource annotation can be specified in any of the classes or their superclasses.

Filter and Annotation_Lương Hoàng Hướng 32


Support for Annotation

❖ Servlet API supports different types of annotations to provide information.


❖ The javax.servlet.annotation package provides annotations to declare
Servlets by specifying metadata information in the Servlet class.
❖ The javax.servlet.annotation package also provides annotations to
declare filters and listeners.
❖ Figure shows how to configure a Servlet by adding annotations to it.

Filter and Annotation_Lương Hoàng Hướng 33


Annotation API
❖ The javax.servlet.annotation package:
❑ Contains a number of annotations Servlets, filters, and listeners.
❑ Provides different types of annotations.
❑ Figure shows the different types of annotations.

Servlet Filter
annotations annotations

Listener Security
annotations annotations

Filter and Annotation_Lương Hoàng Hướng 34


Servlet Annotation
❖ Some of the annotations used by the Servlet are as follows:
❑ WebServlet:
 This annotation is used to provide the mapping information of the Servlet.
 Table shows the attributes of @WebServlet annotation.
Attribute Name Description
name Specifies the Servlet name. This attribute is optional.
description Specifies the Servlet description and it is an optional
attribute.
displayName Specifies the Servlet display name, this attribute isoptional.
urlPatterns An array of url patterns use for accessing the Servlet, this
attribute is required and should register one url pattern.
asyncSupported Specifies whether the Servlet supports asynchronous
processing or not, the value can be true or false.
initParams An array of @WebInitParam, that can be used to pass
servlet configuration parameters. This attribute is optional.
loadOnStartup An integer value that indicates servlet initializationorder,
this attribute is optional.
smallIcon A small icon image for the servlet, this attribute is optional.
largeIcon A large icon image for the servlet, this attribute is optional.
Filter and Annotation_Lương Hoàng Hướng 35
Servlet Annotation
❖ The code snippet demonstrates how to assign @WebServlet annotation to
the Servlet class.

Filter and Annotation_Lương Hoàng Hướng 36


Servlet Annotation

❖ To avoid this wastage of time, there is an option to disable annotation using


the metadata-complete attribute in the web.xml file.
❖ The code snippet shows how to disable annotation in the Servlet files with
version 2.5.

Filter and Annotation_Lương Hoàng Hướng 37


Servlet Annotation
❑ WebInitParam:
 This annotation is used to specify the initialization parameters.
 This can be used with Servlets as well as filters.
 Table shows the attributes of @WebInitParam annotation.

Attribute
Name Description
name Specifies the names of the initialization parameters.
value Specifies the value for the initialization parameters.

Filter and Annotation_Lương Hoàng Hướng 38


Servlet Annotation
❖ The code snippet shows how to apply the @WebInitParam annotation to
the servlet.

Filter and Annotation_Lương Hoàng Hướng 39


Listener Annotations
❖ The Servlet API provides different types of listener interfaces to handle
different events.
❖ To handle HttpSession life cycle events, the HttpSessionListener can
be used.
❖ To declare a class as a listener class, the @WebListener annotation can be
used.

Filter and Annotation_Lương Hoàng Hướng 40


Listener Annotations
❖ The @WebListener annotation is used to register the following types of
listeners:

Context Listener •javax.servlet.ServletContextListener

•javax.servlet.ServletContextAttributeList
Context Attribute Listener ener

Servlet Request Listener •javax.servlet.ServletRequestListener

Servlet Request Attribute •javax.servlet.ServletRequestAttributeList


Listener ener

Http Session Listener •javax.servlet.http.HttpSessionListener

•javax.servlet.http.HttpSessionAttributeLi
Http Session Attribute Listener stener

Filter and Annotation_Lương Hoàng Hướng 41


Listener Annotations
❖ The code snippet shows the implementation of the class that will log the
session created or destroyed.

Filter and Annotation_Lương Hoàng Hướng 42


Listener Annotations
❖ The code snippet shows the Servlet class to create the HttpSession object.

Filter and Annotation_Lương Hoàng Hướng 43


Filter Annotation

❖ In a Web application, the @WebFilter annotation is used to define a filter.


❖ It is specified on a class and contains metadata regarding the filter being
declared.
❖ At least one URL pattern must be specified with the annotated filter.
❖ The urlPatterns or value attribute on the annotation accomplishes this.
❖ The other attributes are optional and have default settings.

Filter and Annotation_Lương Hoàng Hướng 44


Filter Annotation
❖ The code snippet shows the creation of filter using @WebFilter annotation.

Filter and Annotation_Lương Hoàng Hướng 45


Security Annotations
❖ Security annotations can be used to specify permission on the methods of the
Servlet class.
❖ Some of the security annotations are as follows:

ServletSecurity
It is used on a Servlet class to specify security constraints to be
enforced by a servlet container on HTTP protocol messages.

HttpConstraint
It is used within the ServletSecurity annotation to represent
the security constraints to be applied to all HTTP protocol methods.

HttpMethodConstr
aint It is used within the ServletSecurity annotation to represent
security constraints on specific HTTP protocol messages.

Filter and Annotation_Lương Hoàng Hướng 46


Dependency Injection Annotation

❖ Dependency Injection (DI) mechanism allows the container to inject the


dependent objects in the application components.
❖ The application components can be dependent on many resources to perform
the necessary operations.
❖ The dependent objects are injected before the life cycle methods are invoked
and before any reference is made to the dependent object.
❖ Servlet API supports various dependency injection annotations for different
types of resources on which Servlet can be dependent. These include:
❑ @Resource
❑ @RJB
❑ @PersistenceUnit
❑ @PersistenceContext
❑ @WebServiceRef

Filter and Annotation_Lương Hoàng Hướng 47


Dependency Injection Annotation
❖ The code snippet demonstrates how to obtain a reference for the data source
in the Servlet class.

Filter and Annotation_Lương Hoàng Hướng 48


Uploading Files with Servlet
❖ A very common requirement of a Web application is to upload the files on the
server.
❖ File can be uploaded on the sever using the following two ways:

1. Client-side file upload

2. Server-side file upload

Filter and Annotation_Lương Hoàng Hướng 49


Client-side Uploading
❖ To upload the files on Web pages, there are some changes required in the
HTML form.
❖ The requirements are as follows:
❑ Create the input element with the attribute type=”file”.
❑ The form method supported for file upload will be POST, as GET method is not
supported in file uploading.
❑ Use the attribute named enctype with the form element.
❖ Table shows the values that can be assigned to the enctype attribute.
Value Description

application/x-www-form- • This is the default value if not specified.


urlencoded • The value ensures that all characters are encoded before they are
sent to the server.

• The value is provided when the form is using a file upload control.
multipart/form-data • It does not encode the characters before sending them in the
request.

text/plain • The value converts the spaces with the "+" symbols, however no
other special characters are encoded.
Filter and Annotation_Lương Hoàng Hướng 50
Client-side Uploading
❖ The code snippet shows the upload.jsp page containing the HTML form
element to upload the file on the server.

Filter and Annotation_Lương Hoàng Hướng 51


Client-side Uploading

❖ Figure shows the output of the JSP page.

Filter and Annotation_Lương Hoàng Hướng 52


Server-side uploading
❖ The HttpServletRequest class includes two methods for handling the
file upload. These are as follows:
❑ Part getPart(String name)
This method extracts the individual parts of the file and returns each as a
Part object.
The Part object belongs to the Part interface and provide methods that
can be used to extract information from the returned Part object.
The information includes the name, the size, and the content-type of the file
returned as a part.
It also provide methods for querying the header content submitted with the
Http request object, writing the part to the external disk, and deleting the
part.
❑ Collection<Part> getParts()
This method returns a collection of Part objects which can be iterated to
extract individual Part object from the collection.

Filter and Annotation_Lương Hoàng Hướng 53


Server-side uploading
❖ The code snippet demonstrates the Servlet code that uploads the file on the
server.

Filter and Annotation_Lương Hoàng Hướng 54


Server-side uploading
❖ The code snippet shows the corresponding web.xml file for configuring
the Servlet.

Filter and Annotation_Lương Hoàng Hướng 55


MultipartConfig Annotation
❖ The javax.servlet.annotation.MultipartConfig
annotation is specified on a Servlet class.
❖ It provides file information to the server while uploading its content.
❖ The information provided by the MultipartConfig annotation is as follows:

The maximum size of the data that can be uploaded on the server

The default location where the file will be uploaded on the server

Filter and Annotation_Lương Hoàng Hướng 56


MultipartConfig Annotation

❖ Table lists the attributes of the MultipartConfig annotation.


Attribute Description
fileSizeThreshold • Specifies the size of the file in bytes.

maxFileSize • Specifies the maximum file limit allowed to upload the file
on the server.
maxRequestSize • Specifies the maximum file size in bytes to be accepted for
encrypted file data sent in the request.
• Specifies the default location for the file upload on the
location server.

Filter and Annotation_Lương Hoàng Hướng 57


MultipartConfig Annotation
❖ The code snippet shows the attributes of @MultipartConfig
annotation that are applied to the Servlet.

Filter and Annotation_Lương Hoàng Hướng 58


Summary

Filter acts as an interface between client and servlet inside the server. It intercepts the request or
response to and from the server. More than one filter can also exist between a client and a servlet.
This is called a filter chain.

The Filter API is a part of the servlet package. It contain interfaces namely, Filter, FilterConfig,
and FilterChain.

All the information about the filter is described within the <filter> element inside the web.xml
file. The filter also needs to be mapped to the servlet for which it will function. This is done by
assigning URL name and servlet name inside the <filter-mapping> element.

The request and response to and from the servlet is manipulated by the filter. The wrapper object of
RequestWrapper or ResponseWrapper classes created by the filter intercepts the request or response
and sends it to the filter.

Filter and Annotation_Lương Hoàng Hướng 59


Summary

Annotation can be defined as metadata information that can be attached to an element within the code to
characterize it. Annotation can be added to program elements such as classes, methods, fields, parameters, local
variables, and packages.

The javax.servlet.annotation package contains a number of annotations Servlets, filters and listeners.
Apart from this, Servlet API also supports various dependency injection annotations.

File can be uploaded on the sever using the following two ways namely, Client-side file upload and

server-side file upload.

The javax.servlet.annotation.MultipartConfig annotation is specified on a Servlet class to provides file


information to the server while uploading its content.

Filter and Annotation_Lương Hoàng Hướng 60

You might also like