Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe for all free courses

@WebFilter annotation for filtering Web Requests in Java EE

A simple Web application to demonstrate @WebFilter annotation for filtering request coming to web server.In this tutorial the filter is printing the remote host IP address on the console.

Click here to download complete source code 

package com.hubberspot.javaee.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

// @WebFilter annotation makes HostFilter class 
// a filter in Java EE application. /* tells
// annotation that filter each and every request
// coming to server. Here the filter prints IP 
// address of the request on the console.
@WebFilter("/*")
public class HostFilter implements Filter {

 private FilterConfig filterConfig;
 
 public void destroy() {
  System.out.println("Destroyed ... ");
 }

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

  String ipAddress = request.getRemoteHost();
  System.out.println("Remote IP Address : " + ipAddress);
  
  // pass the request along the filter chain
  chain.doFilter(request, response);
 }

 public void init(FilterConfig fConfig) throws ServletException {
  this.filterConfig = fConfig;
 }

}




Output of the program : 


 


Video tutorial to demonstrate @WebFilter annotation for filtering request coming to web server.In this tutorial the filter is printing the remote host IP address on the console. 




Using annotation







 
© 2021 Learn Java by Examples Template by Hubberspot