Home » Struts 2 ServletContextAware interface example

Struts 2 ServletContextAware interface example

by Online Tutorials Library

ServletContextAware Interface Example

The ServletContextAware interface must be implemented by the Action class to store the information in the application scope.

It contains only one method setServletContext. Syntax:

Usage of ServletContextAware interface

There can be a lot of real usage of ServletContextAware interface. They are:

  • You can hold all the records of a table in the ServletContext object using collection and get these information from any action class. In this way, performance of the web application will be increased.
  • You can store the Connection object and get the connection object from any action class etc.

Example of ServletContextAware interface

In thie example, we are creating two links first page and second page. If you direct click on the second page, it will not show any data but if you have clicked on the first link, data will be stored in the ServletContext object and it can be obtained from another action class. In the second link, we are getting data stored in the ServletContext object.

In this example, we are need following pages

  1. index.jsp for providing links to the first and second action.
  2. struts.xml for defining the result and action.
  3. FirstAction.java for storing data in the ServletContext object.
  4. SecondAction.java for fetching data from the ServletContext object.
  5. View components for the displaying results.

1) Create index.jsp for input

This jsp page creates two links, first link invokes first action class and second link invokes second action class.

index.jsp

2) Define action and result in struts.xml

This xml file defines one package and 2 actions.

struts.xml

3) Create the action class to store data

This action class implements the ServletContextAware interface and overrides the setServletContext method to store the information in the application scope.

FirstAction.java

4) Create the action class to get data

This class gets the information from the application scope, if any information is found in the session scope with login name, it returns success otherwise false.

SecondAction.java

5) Create view components

There are many view components:

  • firstsuccess.jsp
  • secondsuccess.jsp
  • seconderror.jsp

firstsuccess.jsp

This page creates the login form.

secondsuccess.jsp

This page prints the welcome message with the username.

seconderror.jsp

This page displays the error message.

You may also like