Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to implement filter in Java Server Page?

In this article we will discuss about the filter implementation in JSP pages.

Let us start with filter in Java Server Page. Actually in modern web technology filter is very popular. Filters are components that sit between a request and the intended endpoint of that request. So it is the client server concept process. The endpoint could be a static (fixed) or dynamic (changing) resource such as a Hypertext Markup Language page, Java Server Page, or a Servlet. The filter which has many activates and all types of activities are important and also it can be able to do many types of jobs. Now we will discuss some most common and important job which is coming from the filter process.

  • Filters can read the request data on the path way to the endpoint process.
  • Filter wraps the request before passing it on the system.
  • It has ability to wrap the response before passing it on.
  • Filter can Influence the response data on the way back to the output process.
  • In that process if any error occurs then it returns the errors to the client machine.
  • When the Request is dispatching to another resource and it ignore the original Uniform Resource Locator then it can engender its own response before returning to the client machine.

The implementation of filter is crucial for any web application. For that reason it is more and more important that developers or the designer have to be very careful when using them. At the time when we are using filters, the developers are much closer to the Hypertext Markup Language protocol than with a Servlet and must apprehend the protocol (set of rules) in much more detail. The illustration, when we use Servlets, a developer can pretty ignore the Hypertext Markup Language content-length header, but when we use the filters and producing the data, then the filter writer may have to know the actual size of the content and set the value of that header. Fundamentally filters exist as part of a sequence; with the last link in the sequence is being the requested resource. Generally the Filter that can indicate to pass the request on here, in which case the request will be progressed to either the next Filter in the Filter sequence otherwise, if this is the last Filter in the sequence, to the requested source. The Filter also use the response before it is returned to the client machine. The following spitting Figure is giving us a real Figure of the client request and the client response and through the container of the filter it is passing through start point to end point.

Showing
request/response in filter

Figure1: Showing request/response in filter

The above Figure shows the actual code path when the Filters are invoked. The client makes a request to a resource, such as a Servlet, Java Server Page, or static file, and the Web Application is configured such that any number of the filters is invoked for the request. Then each Filter is invoked in turn, and every Filter passes on the request down the filter sequence until the endpoint is executed. Filters are very helpful because they allow a Web developer to cleanly add any number of the layers of pre-processing and post-processing to a request and response. Basically the functionality can be mimicked using servlets and request transmitting, but it is a slightly complex approach and requires forwarding all requests through one or more Servlet before reaching the finally endpoint position. By using the Filters it is easy to effortlessly define and apply a Filter to existing Web Application resources. The Servlet 2.4 requirement further extends the utility of the Filters. It is now possible to install Filters that get invoked on a Request Dispatcher to forward or include or that get invoked in the case of an error.

The Filter Life Cycle

The Filter life cycle is conceptually identical to the three-phase Servlet life cycle processes. The life of a Filter goes through initialization, service, and destruction. First, the initialization occurs only once at the time of loading which will be used by a Web Application. The service phase is the main phase for executing filter logic. It is invoked each time the Filter is applied to a request and response. At last the destruction phase is invoked after a Web Application is completely finished using the Filter and all resources of the Filter need to be properly terminated. Figure 2 illustrates the Filter life cycle.

Compared to the Servlet life cycle, it includes the exact same init () and destroy () methods matching initialization and destruction phases, respectively. The only difference is the new doFilter() method that corresponds to the service phase of the life cycle. The doFilter () method is the main method invoked by a container when applying a Filter to a ServletRequest and ServletResponse. Both the request and response are passed as parameters to this method and that is where the Filter is customized to do its specific task.

Filter Life Cycle

Figure2: Filter Life Cycle

Coding a Simple Filter

A Filter must implement the javax.servlet.Filter interface. This interface defines the life cycle of a Filter and implements a custom Filter that generally supports all the required methods.

The Filter interface defines three methods respectively as shown in the table below:

Sl

Method

Application

1

void init(FilterConfig config) throws ServletException

This function is defined for the initialization. The init()method is directly called at the time when container is loading. This method is generally used to collect the initialization of the parameters (actually it is called arguments) from the web.xml file and it also execute any different initialization code that is engaged in the function or the method. It is passed the reference to a FilterConfig object which is issued to access the initialization data. These types of function are called only one time.

2

void destroy():

This destroy method is used for the destruction of the systems. The destroy () method is generally invoked at the time when filter is destroyed or unloaded from the computer memory. So we can clearly say that it generally occurs at the time of shutdown of the systems. The destroy () method is very popular to properly end any type of external resources which is initialized by the Filter process.

3

void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException

This is the method that is very popular for filter related work. The doFilter() method is no doubt very necessary at time of request and response types of method. There are generally three types of parameters passing through the method. We can easily illustrate that this method is an instance of a ServletRequest, ServletResponse, and the FilterChain object also present of the systems. In that case ServletRequest and ServletResponse objects are instances of HttpServletRequest and HttpServletResponse. There are many types of methods necessary for working with filter related jobs. Some available parameters for those types of method are like that HttpServletRequest and HttpServletResponse objects, correspondingly.

Table1: Showing filter methods

Like the service method in servlet, the doFilter() method may be called by multiple threads simultaneously. Naturally the FilterConfig object is used for the Filter configuration, and the FilterChain object signifies with the contemporary sequence of the Filters is being functional to a request and response process. Now let us take an example that gives us standard way of filter programming.

Listing 1: Sample filter program

  import java.io.*; //import java input output   
  import javax.servlet.*; //import servlet package 
  import javax.servlet.http.*; 
  public class HelloBCEI implements Filter
  {
                  public void init(FilterConfig config)
  {
                 // Do initialization
  }
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain filter)
  throws IOException, ServletException 
  {
  HttpServletRequest request = (HttpServletRequest)req;
  HttpServletResponse response = (HttpServletResponse)res;
  response.setContentType("text/html");
  PrintWriter out = response.getWriter(); //initialization of the out object
  out.println("<html>");
  out.println("<head>");
  out.println("<title>Welcome to Mrbool…</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<h3>Hello MrBool!</h3>");
  out.println("</body>");
  out.println("</html>"); //End of the html code
  return;
  }
  public void destroy()
  {
                  //Write the information at the shutdown the system
  }
  }
  

Showing
out put

Figure 3: Showing out put

After the running the programs through Net Beans IDE 7.2 a standard output will be displayed as shown above.

Now save the program as HelloBCEI.java in /WEB-INF/classes/com/bceibook directory of the bceibook Web Application. After that just compile the respective code and find out if any error occurs in the system. Remember that before the seeing any result the Filter needs to be deployed within the Web Application system. The positioning of a Filter is unexpectedly same as in Servlet programming approach. The only difference is the name of the attributes used in web.xml, instead of the servlet, as well as the servlet-name, and servlet-class elements, the filter, filter-name, and filter-class elements are also used. Generally three new elements are provided with the actual standard functionality.

Now here we illustrate an example of the HelloBCEIFilter.xml. This example saves with xml extension

Listing 2: Sample xml file (HelloBCEIFilter.xml)

  <filter>
  <filter-name>HelloBCEIFilter……</filter-name>
  <filter-class>com.bcei.HelloBCEIFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>HelloBCEIFilter…</filter-name>
  <url-pattern>/HelloBCEIFilter….</url-pattern>
  </filter-mapping>
  

Now save the changes and reload the bceibook through the Web Application. Then for reloading the system, just click on following uniform resource locator http://127.0.0.1/bceibook/HelloBCEI Filter to see the newly added Filter in use. It should be clear that a Filter can do exactly what a servlet can do. This HelloBCEI example is the simple and direct way; nevertheless point should be remembered that Filters are also present in Servlet with some extra functionality.

Filter Configuration

Here we will discuss about the filter configuration. Because, we need to know filter configuration process to use the architecture efficiently. Basically it is true that filter configuration is almost same as the servlet. The Filter web.xml element may be containing at any numbers of init-param so that elements to delimit with the custom initialization parameters process.

Here we will discuss some important functions interrelated with the filter configuration process.

Sl

Function

Application

1

String getFilterName()

This getFilterName is one of the most important methods for the filter configuration process. This method is a return type method as it returns string. It will generally return the name of a Filter as it is already defined in the Filter’s web.xml entry location.

2

String getInitParameter(String name)

Now another function name is getInitParameter(),it is also returns string return type, it returns the value coordinated to the name of the given initial parameter name. The parameter’s name and value or data are defined by the param-name and param-value elements, correspondingly, in the Filter’s web.xml entry. At the movement of the checking procedure if the system cannot find any data or information then null value will be returned.

3

Enumeration getInitParameterNames()

This is another return type method. The getInitParameterNames () method returns a java.util. The Enumeration objects are counting all of the Filter’s initial parameter names. So the initial parameter names are the same as the ones distinct by the param-name elements of the Filter’s in the web.xml entry.

4

ServletContext getServletContext()

This is the servlet base return type function. This method is interrelating with the filter. The getServletContext () method also returns the ServletContext of the Filter in the Web Application form.

Table2: Showing important filter functions

Processing to Provide Java Server Page-Replacing Functionality through filter

Servlet and Java Server Pages have been treated as complementary technologies that we should use at the time of constructing Web Applications. In some cases there is a difference. The standardized Extensible Markup language is a styling mechanism of the eXtensible Stylesheet Language Transformations (XSLTs). XSLT is very much prevalently required with many Extensible Markup language projects that are also together with Java Extensible Markup language projects.

We can work on projects with a group of XML/XSLT designing. Now it makes little sense to completely drop XSLT in favor of learning Java Server Page. In that circumstance the very well explanation would be to twig with Extensible markup language/XSLT and build a Filter which takes care of the requirements. It is clear that filter is not problematic or rigid to build and it could very effortlessly control the interrupting requirements. As an alternative way to showing the resources ending in Extensible Markup language, here the Filter might automatically relate an XSLT stylesheet and it will return the transformed content. We are now familiar with XSLT, and the Filter could additionally do a check to see if the client can do the transformations. When such types of cases occur then the filter could purely give the fresh Extensible Markup language and XSLT to a customer and easily by pass doing a server-side renovation altogether. A Java Server Page replacing the filter will not be established. In that manner the very positive and significant argument to take away from this segment is that filters are part of the Servlet measurement and are not tied to Java Server Page. We would be desired to use a Java Server Page by replacing technology for style; in that scenario we say positively that filters are ultimate choices for the Web Application implementation of all types.

Conclusion

Filter in Java Server Pages is very important concept in our software development field. Filters are an extremely powerful addition to the Servlet specification. We have already discussed that filters can be used easily by following proper steps and process. It allows the manipulation of data both before and after the resource has performed and in a method that is cleanly implemented. The Filters will be required for many things from the data manipulation, through logging and security. So the filters can be used in different levels through proper configuration.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login