Free Data Structures and Algorithms Course









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










OR



Subscribe to 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







How to use @WebInitParam annotation for setting initialization parameters in Servlet ?.

A simple HelloWorldServlet demonstrating usage of @WebInitParam annotation for setting initialization parameters.

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
    , initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Hello " 
      + getServletConfig().getInitParameter("user") 
      + "</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}




Output of the program : 


 

How to determine active users / sessions in a Java Web Application ?.

A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.

package com.hubberspot.javaee.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUsersCounter implements HttpSessionListener {

 private static int numberOfUsersOnline;
 
 public OnlineUsersCounter() {
  numberOfUsersOnline = 0;
 }
 
 public static int getNumberOfUsersOnline() { 
  return numberOfUsersOnline;
 }
 
    public void sessionCreated(HttpSessionEvent event) {

     System.out.println("Session created by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline++;
  }
     
    }

    public void sessionDestroyed(HttpSessionEvent event) {
     
     System.out.println("Session destroyed by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline--;
  }

    }
 
}



Running the below servlet on three different browsers will provide output as : (see fig below)

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hubberspot.javaee.listener.OnlineUsersCounter;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
    , initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
  
  // sessionCreated method gets executed
  HttpSession session = request.getSession();
  
  session.setMaxInactiveInterval(60);
  
  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Number of Users Online : " 
      + OnlineUsersCounter.getNumberOfUsersOnline() 
      + "</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }
        
 }

}



Output of the program : 

1. Eclipse Browser
























2. Firefox Browser



3. Internet Explorer Browser

 
 4. Console Output


 

How to create a Listener using @WebListener annotation ( ServletContextListener ) in Java EE application ?.

Program to demonstrate creation of a ServletContextListener using @WebListener annotation.

package com.hubberspot.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

// @WebListener annotation informs container that
// this class is a web listener which will listen to
// various events happening during lifecycle of application
// Here this class listens to StartUp and ShutDown of the
// application.

// We make class implements ServletContextListener which has two
// methods contextInitialized() and contextDestroyed() , which
// are called by the container whenever a servlet context is 
// started or shutdown

@WebListener
public class StartStopAppListener implements ServletContextListener {

 public void contextInitialized(ServletContextEvent servletContextEvent) {

  System.out.println("Servlet Context Initialized ... ");

 }

 public void contextDestroyed(ServletContextEvent servletContextEvent) {

  System.out.println("Servlet Context Destroyed ... ");

 }

}




Output of the program : 


 

HttpSessionAttributeListener example using @WebListener annotation.

Program to demonstrate how to apply listener to Session attributes in Java EE

package com.hubberspot.javaee.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

// @WebListener annotation informs container that
// this class is a web listener which will listen to
// various events happening during lifecycle of application
// Here this class listens to changes made to HttpSession 
// attributes.

// We make class implements HttpSessionAttributeListener
// which has three methods : attributeRemoved(), attributeAdded() 
// and attributeReplaced() , which are called by the container
// whenever attributes are added, removed, or replaced 
// within the HTTP session.

@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {


    public void attributeRemoved(HttpSessionBindingEvent event) {

     System.out.println("Method called when HttpSession attribute removed :");
     HttpSession session = event.getSession();     
     System.out.println("Session ID : " + session.getId());
     System.out.println("Session Name : " + event.getName());
     System.out.println("Session Value : " + event.getValue());
     
    }

    public void attributeAdded(HttpSessionBindingEvent event) {

     System.out.println("Method called when HttpSession attribute added :");
     HttpSession session = event.getSession();     
     System.out.println("Session ID : " + session.getId());
     System.out.println("Session Name : " + event.getName());
     System.out.println("Session Value : " + event.getValue());
     
    }

    public void attributeReplaced(HttpSessionBindingEvent event) {

     System.out.println("Method called when HttpSession attribute replaced :");
     HttpSession session = event.getSession();     
     System.out.println("Session ID : " + session.getId());
     System.out.println("Session Name : " + event.getName());
     System.out.println("Session Value : " + event.getValue());
     
    }
 
}


Run HelloWorldServlet.java and methods mentioned in above listener will be called by the container.


package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
    , initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
  
  HttpSession session = request.getSession();
  
  // attributeAdded method gets executed
  session.setAttribute("user", "Jonty");
  
  // attributeReplaced method gets executed
  session.setAttribute("user", "Dinesh");
  
  // attributeRemoved method gets executed
                session.removeAttribute("user");

 }

}


Output of the program : 


 

Using @WebServlet annotation to register Servlets without using web.xml

With the introduction of Annotations in Java, now its easy to remove xml configuration files with annotations. Registering each and every servlet in web.xml is quite hectic task. In order to avoid this, @WebServlet annotation is used. This post creates a simple Servlet named as HelloWorldServlet without making any registry in web.xml file.
@WebServlet annotation is used over the class level.  

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" })
public class HelloWorldServlet extends HttpServlet {

 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Hello World !!!</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}



Here in above HelloWorldServlet @WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }) is equivalent to
<servlet>
    <servlet-name>HelloWorldServlet</servlet-name>
    <servlet-class>com.hubberspot.javaee.HelloWorldServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>HelloWorldServlet</servlet-name>
    <url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>



Output of the program : 


 

Dynamic loading of JDBC (Database) Connection Properties in Java

Program to demonstrate how to load JDBC Connection properties in Java dynamically.

1. Create JDBC Database Connection Properties file for MySql (connection.properties)

# Database Properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/sample
database.user=root
database.password=root


2. Create a Java class for loading of this properties.
package com.hubberspot.example;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class DatabaseConnection {

 public static void main(String[] args) throws IOException {
 
  File propertiesFile = new File("F:/Java/Spring/workspace/Java/src/connection.properties");
  FileReader fileReader = new FileReader(propertiesFile);
  
  Properties props = new Properties();
  props.load(fileReader);
  
  String driver = props.getProperty("database.driver");
  String url = props.getProperty("database.url");
  String user = props.getProperty("database.user");
  String password = props.getProperty("database.password");
  
  System.out.println("Driver : " + driver);
  System.out.println("Url : " + url);
  System.out.println("User : " + user);
  System.out.println("Password : " + password);

 }
 
}



Output of the program :



In future, if you wish to change the database say from MySql to Oracle, than just you need to change connection.properties file.See below :

1. Create JDBC Database Connection Properties file for Oracle (connection.properties)

# Database Properties

database.driver=oracle.jdbc.driver.OracleDriver
database.url=jdbc:oracle:thin:@localhost:1521:sample
database.user=root
database.password=root


After running the above Java class again we get the output as :

Output of the program : 

 


 
© 2021 Learn Java by Examples Template by Hubberspot