Pages Navigation Menu

Coding is much easier than you think

Login Interceptor in Struts 2

Posted by on Aug 5, 2014 in Struts-2 | 7 comments

 
In our previous tutorial we have learned about concepts of interceptor and how interceptors gets execute before and after action class by creating a custom interceptor. In this article we shall create a custom LoginInterceptor which could be used in real time struts 2 application
 
Login Interceptor in Struts 2
 
This LoginInterceptor will perform these tasks:-

  • Check user exist in session or not.
  • Runs before every action to check .If someone try to access direct URL of welcome page and if he is not present in session then it will redirect towards login page.
  • If user already in session then call the action called by user.
  • If session time expired and if user clicks on any link, then redirect towards login page.

 
File : LoginInterceptor.java
 

package com.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor  extends AbstractInterceptor {

        @Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map session = invocation.getInvocationContext().getSession();

		String loginId = (String) session.get("loginId");

		if (loginId == null) 
		{
			return Action.LOGIN;
		} 
		else 
		{
			return invocation.invoke();
		}
	}
}

 
Here LoginInterceptor class extended the “AbstractInterceptor” and in its intercept method we have written business which checks weather the user present in session or not.

In the intercept method, we can make use of com.opensymphony.xwork2.ActionInvocation i.e. Action Invocation object to get the action name trigger and decide on the further flow of application associated with it. On the similar lines we can also make use of the org.apache.struts2.ServletActionContext to get the request, response, session object etc. which can be used further to decide on flow of the application.

 
LoginAction.java
 

package com.action;

import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;
	private String userName;
	private Map session;

	public String home() {
		return SUCCESS;
	}

	// Log Out user
	public String logOut() {
		session.remove("loginId");
		addActionMessage("You have been Successfully Logged Out");
		return SUCCESS;
	}

	// Login user
	public String login() {
		if (userName.isEmpty()) {
			addActionError("Username can't be blanked");
			return LOGIN;
		} else {
			session.put("loginId", userName);
			return SUCCESS;
		}
	}

	public String getUserName() {
		return userName;
	}

	public Map getSession() {
		return session;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setSession(Map map) {
		this.session = map;
	}
}

 
LoginAction class with simple business logic, such as you can login with any username but cannot leave blank the mandatory fields.
 

Configuring the custom interceptors in struts.xml

 
Here we configure our custom interceptor named LoginInterceptor defining loginStack as default stack.
 



	
		
		
		
			
			
		
	

	
	
		homeAction
		login.jsp
	

	
	
		
		login.jsp
		home.jsp
	
	
	
	
		login.jsp
	


 

web.xml:

 
In web.xml define session time out to 1 min, for demonstrating point 4
 

  
    struts2
    
	org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
  
  
    struts2
    /*
  
  
    1
  
  
    login.jsp
  

 

Demo

Now on running this application
 
Login Interceptor
 
Now on entering a valid User name and hitting Submit button, the following page get appeared.
 
Login Interceptor2
 
Now once I hit logout link or if the session gets expired, then if the try to access the localhost:8089/LoginInterceptor/homeAction url, then the application redirects to Login page as shown below.
 
Login Interceptor
 

Read More

Interceptors in Struts 2

Posted by on Aug 3, 2014 in Struts-2 | 0 comments

 

  • Interceptors are introduced as part of the Struts2 framework, power mechanism for controlling request and are responsible for the most of request processing.

 
Request Processing Life Cycle Workflow in Struts 2

  • Interceptors are invoked by controller before and after invoking action and sits between the controller and action.
  • An interceptor allows common, cross-cutting tasks to be defined into a clean, reusable component, which is different than the “action” code.
  • Tasks like data validation, type conversion, and file upload are done using interceptors in Struts2.0.
  • The built-in interceptors, declared in the “defaultStack” of the “struts-default package”, handle most of the fundamental tasks.

 

Functioning of Interceptors

  • From architectural point of view, interceptors improve separation of concerns in web applications.
  • An example of a pre-processing task is the data transfer achieved with the “params” interceptor.
  • Instead of having a simple controller that directly invokes an action, we now have a component that sits between the “controller” and the “action”.
  • In Struts 2, no action is invoked in isolation, the invocation of an action is a layered process. It always includes the execution of a stack of interceptors prior to and after the actual execution of the action itself.
  • Rather than directly invoking the action’s execute ( ) method, the framework creates an object called an “ActionInvocation”. This object encapsulates the action. Subsequently, all the interceptors that have been configured to fire before and after that “action” start their execution.

 

Interceptor Order

Diagrammatic Representation

actioninvocation

  • The figure above represents the normal workflow; here none of the interceptors have diverted the invocation. This “action” will ultimately execute and return a “control string” that selects the appropriate “result”.
  • After the “result” execution, each of the interceptors, in reverse order, gets a chance to do some post-processing work.
  • As we will see, the interceptors have access to the “action” and other contextual values. This allows them to be aware of what is happening during the processing.
  • One of the powerful functional aspects of “interceptors” is their “ability to alter the workflow of the invocation”.
  • As we noted, the figure shown in the above depicts an instance where none of the interceptors has intervened in the workflow. It thus allows the “action” to execute, and determine the result that should render the view.
  • Sometimes, one of the interceptors will determine that the “action should not execute”. In such cases, the interceptor can halt the workflow by itself by returning a “control string”.

 
In our next article we shall learn to implement a custom interceptor in struts 2
 

Read More

GridView in Struts2 using jQuery DataTable via Ajax

Posted by on May 31, 2014 in Ajax, jQuery, Struts-2 | 17 comments

 
In this post, I am going to explain on how to use DataTable plugin to display data in Gridview format with pagination feature in Struts 2 web application.
 
Gridview in Struts2 using jQuery DataTable plugin
 
DataTable is a jQuery plugin which adds a lot of functionality to plain HTML tables, such as filtering, paging sorting, changing page length, server side processing etc.
 

Library

In this example, I am going to retrieve values from a csv file and display it in html table. For this, I am going to use OpenCSV library which simplifies the work of parsing CSV files. Here the Data table will load the data by making an Ajax call.
 
Note:
• Refer the article on how to Read / Write CSV file in Java using Opencsv library/ .
 
Since the response to be generated from the action class is of type JSON, So to handle it you need struts2-json-plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute (which has getter and setter) into a JSON object. Refer this article here for more detail.
 
Now create a dynamic web project in eclipse and create two folders named ‘js’ and ‘css’ under WebContent, and add the following javascript files from DataTable to the ‘js’ folder

• jquery.dataTables.js
• jquery.js

Add the following css files from DataTable & jQuery ui to ‘css’ folder.

• demo_page.css
• demo_table_jui.css
• jquery-ui-x.x.x.css
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Download the csv file from which the data is to be read from here and place it under src folder, This files contains four columns – company, country, revenue, and year.
 

Project Structure

 
Folder structure - Gridview - Struts2 - DataTable 2
 

Model class

 
Create a model class that gets and sets the data from the four columns (company, country, revenue, and year) of the csv file.
 

package com.model;

public class RevenueReport {

	public RevenueReport(String company, String country, String year,
			String revenue) {
		this.company = company;
		this.country = country;
		this.year = year;
		this.revenue = revenue;
	}

	private String company;
	private String country;
	private String year;
	private String revenue;

	public String getCountry() {
		return country;
	}

	public String getRevenue() {
		return revenue;
	}

	public String getCompany() {
		return company;
	}

	public String getYear() {
		return year;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public void setRevenue(String revenue) {
		this.revenue = revenue;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public void setYear(String year) {
		this.year = year;
	}
}

 

Business class

 
Create a Business Service class that would fetch data from the csv file using model class.
 

package com.service;

import java.io.*;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;

import com.model.RevenueReport;

public class BusinessService {

public static List getCompanyList() {

	List listOfCompany = new LinkedList();
	String fileName = "Company_Revenue.csv";

	InputStream is = Thread.currentThread().getContextClassLoader()
			.getResourceAsStream(fileName);
	BufferedReader br = new BufferedReader(new InputStreamReader(is));

	try {
		CSVReader reader = new CSVReader(br);
		String[] row = null;
		while ((row = reader.readNext()) != null) 
		{
		listOfCompany.add(new RevenueReport(row[0], row[1], row[2],	row[3]));
		}
		reader.close();
	} catch (IOException e) {
		System.err.println(e.getMessage());
	}
	return listOfCompany;
}
}

 

Jsp

 
Now create the jsp file to display the data fetched from csv file in html table and enhance the table features using DataTable plugin.
 




Gridview in Struts2 using jQuery DataTable plugin












Ajax based Gridview in Struts2 using jQuery DataTable plugin

Company Country Year Revenue

 
Do read :

  • jQuery Tutorial for Beginners
  • Autocomplete in Java web application using jQuery
  • Tab Style Login and Signup example using jQuery in Java web application
  •  

    Action class

     
    In reply to each request for information that DataTables makes to the server, it expects to get a well formed JSON object with the parameter below.

    1. aaData- The data in a 2D array.
     

    package com.action;
    
    import java.util.List;
    
    import com.model.RevenueReport;
    import com.opensymphony.xwork2.Action;
    import com.service.BusinessService;
    
    public class GridViewAction implements Action {
    
    	private List aaData;
    
    	public List getAaData() {
    		return aaData;
    	}
    
    	public void setAaData(List aaData) {
    		this.aaData = aaData;
    	}
    
    	public String execute() {
    		aaData = BusinessService.getCompanyList();
    		return SUCCESS;
    	}
    }
    

     

    struts.xml

     

    
      	
    		
                            
                               true
                              true
                           
    		
    	
    	
    
    

    Note that I have extended “json-default” package instead of struts-default package and I have set the result type to json, I have explained about the reason for extending “json-default” package in the article AJAX implementation in Struts 2 using JQuery and JSON, please refer the mentioned link if you are not aware of the same.
     

    Recommended reading:

  • Ajax in struts 2 implementation without jQuery library
  •  

    web.xml

     
    Make sure you have done servlet mapping properly in web.xml file as shown below

    
    Struts2
    
    	struts2
    	
    	 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            
    
    
    	struts2
    	/*
    
    
    	index.jsp
    
    
    

     

    Demo

     
    Gridview in Struts2 using jQuery DataTable plugin
     
    download

    Read More

    Struts 2 and Tiles Framework Integration

    Posted by on May 5, 2014 in Struts-2 | 2 comments

     
    Apache Tiles is a templating framework used to simplify the development of web application user interfaces. Tiles allow defining page fragments which can be combined into a complete page at runtime. These fragments, or tiles, can be used as reusable templates in order to reduce the duplication of common page elements or even embedded within other tiles. See the snapshot below.
     
    ** UPDATE: Struts 2 Complete tutorial now available here.
     
    tiles layout in struts 2

    Advantage of tiles framework

    • Code reusability
    • Easy to modify
    • Easy to remove

    Jar Required

     
    struts 2 - tiles library required

    Folder structure

     
    struts 2 - tiles library required
     

    web.xml

     
    Provide entry of listener class Struts2TilesListener in the web.xml file.

      
        org.apache.struts2.tiles.StrutsTilesListener
      
    

     

    Recommended Article

     

    Jsp Pages

     
    Now We will define the template for our web application in baseLayout.jsp file. This template will contain different segments of web page (Header, Footer, Menu, Body).
     
    File : baseLayout.jsp

    <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
    
    
    
    
    <tiles:insertAttribute name="title" ignore="true" />
    
    
    
    

     
    File : header.jsp

    
    
    
    Struts 2 - Tiles Demo - Header page

     
    File : footer.jsp

    
    
    
    Footer page © SimpleCodeStuffs.com

     
    File : body.jsp

    
    
    	

    Home Page

     
    File : menu.jsp

    <%@taglib prefix="s" uri="/struts-tags"%>
    
    
    	
    	
    	
    Menu



    Struts Tutorial

    Spring Tutorial

     
    File : springTutorial.jsp

    
    
    

    Spring Tutorial !!!

     
    File : strutsTutorial.jsp

    
    
    	

    Struts Tutorial !!!

     
    File : index.jsp
    It triggers homeAction during application start up

    
    

     

    Action Class

     

    package com.simplecodestuffs.action;
    
    public class TilesAction {
    
    	public String home() {
    		return "home";
    	}
    
    	public String struts() {
    		return "struts";
    	}
    
    	public String spring() {
    		return "spring";
    	}
    }
    

     

    struts.xml

     
    In struts.xml, inherit the tiles-default package and define all the result type as tiles

    
    
    
    
    	
    		home
    		struts
    		spring
    	
    
    
    

     
    Do read :

     

    tiles.xml

     
    The tiles.xml file must be located inside the WEB-INF directory, in which define all the tiles definitions

     
    
    
    
    
    
    
    	
    	
    	
    	
    	
    
    
    
    	
    	
    
    
    
    	
    	
    
    
    
    	
    	
    
    
    
    

     

    Demo

     
    Home Page with Tiles
    struts 2 tiles home page
     
    Struts Page with Tiles
    struts 2 tiles
     
    Spring Page with Tiles
    tiles struts 2
     

    How to define multiple tiles files in struts 2 application?

     
    To define multiple tiles, you need to add following entry in your web.xml file.

      
    org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
      
    
    /WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml  
      
    

     

    dwd2
    Download It – Struts2-Tiles

     

    Read More

    Struts2-Jfreechart integration

    Posted by on May 1, 2014 in JFreeChart, Struts-2 | 3 comments

     
    In this article we will learn to integrate Struts 2 with JFreeChart using struts2-jfreechart-plugin-x.x.x.jar for creating a pie chart in web application using JFreeChart library.
     
    The JFreeChart is easiest and the most widely used library for creating a wide variety of good looking charts.

    The Struts-JFreeChart plugin allows Struts 2 Actions to easily return generated charts and graphs.

    Instead of streaming a generated chart directly to the HTTP response, this plugin provides a ChartResult, which handles the generation for you. This allows you to generate the chart in one class, and render it out in another class, effectively decoupling the view from the Actions.
     
    ** UPDATE: Struts 2 Complete tutorial now available here.
     

    Libraries required :

    Jfreechart library can be downloaded here.
     
    Now Create a New Dynamic Web Project in eclipse with following folder structure
     
    Struts2-Jfreechart Folder structure
     

    Struts 2 Action

     
    File : JfreeChartAction.java

    package com.simplecodestuffs.action;
    
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.JFreeChart;
    import org.jfree.data.general.DefaultPieDataset;
    
    import com.opensymphony.xwork2.Action;
    
    public class JfreeChartAction implements Action {
    
         private JFreeChart chart;
    
         public String execute() throws Exception {
    
    	DefaultPieDataset dataSet = new DefaultPieDataset();
    	dataSet.setValue("Agriculture", 10);
    	dataSet.setValue("Residential heating", 4);
    	dataSet.setValue("Commercial products", 15);
    	dataSet.setValue("Industry", 42);
    	dataSet.setValue("Transportation", 26);
    	dataSet.setValue("Others", 3);
    
    	chart = ChartFactory.createPieChart(
    		"Source of Air Pollution ", // Title
    		dataSet,                    // Data
    		true,                       // Display the legend
    		true,                       // Display tool tips
    		false                       // No URLs
    		);
    
    	chart.setBorderVisible(true);
    
    	return SUCCESS;
    	}
    
         // This method will get called if we specify chart
         public JFreeChart getChart() {
    	return chart;
         }
    }
    

     

    Recommended reading:

     
    Here Jfreechart provides DefaultPieDataset method to set static data and createPieChart() method creates the pie chart using the dataset.
     

    struts.xml

     
    To use the plugin, have your Struts configuration package extend the jfreechart-default package, which provides the chart result type.
     

    
    
    
       
       
           
                
    		chart
    		jpeg
    		600
    		400
    	    
    	
       
    
    

     

    Jsp page

     

    
    
    Struts2-Jfreechart integration
    
    
         

    Struts2-Jfreechart integration


     
    In Jsp, servlet is called via img tag’s src attribute. This triggers the Action and render the image on the page.
     
    ** UPDATE: To Create Auto-Refreshing Pie Chart dynamically the following tutorial will help here.
     

    Demo

     
    Now right click on the project name and select Run As –> Run on Server.
     
    Struts2-Jfreechart integration
     
    download

    Read More

    Introduction to Struts 2 Framework

    Posted by on Mar 20, 2014 in Struts-2 | 0 comments

     
    In our last article we have learned about the difference between Model 1 and Model 2 (MVC) Architecture. In this article we will learn about Struts 2 framework and about the Architecture which it follows.
     
    In general if you are about to build a standard application using JSP and Servlets, then you will end up in a following MVC pattern.
     
    MVC Basic flow
     
    ** UPDATE: Struts 2 Complete tutorial now available here.
     

    Why web Framework ?

     
    Web framework is a basic ready made underlying of MVC structure, where you have to just add components related to your business. It forces the team to implement their code in a standard way. (helps debugging, fewer bugs etc).

     

    Step involved in building a framework.

     
    Step 1: Router to route the request to the correct MODEL and correct View layer

    Step 2: Handle the request parameters

    Step 3: Create a interface class(Model) for business service class

    Step 4: View part(Jsp) to render the result

     
    The above steps are depicted photographically below.
     
    Frame work architecture
     
    Struts 2 developers have identified all these modules and had builded the same. Below is how a struts 2 design will look like.
     
    Struts 2 high level framework architecture
     
    Here Interceptor is the gate way through which a request is passed. It takes care of getting user request parameters,
     
    Struts 2 framework get all the request parameters from interceptor and makes it available for Action class and we don’t need to fetch it in the action class via any request or session objects like we do in Servlets, because struts 2 makes it available.
     
    Here Struts.xml acts as controller which Controls the execution flow of the request, Action class represents Model and JSP represent View layer.
     
    Note:
     
    In struts 2 the data can be displayed in jsp with tab library,
     
    In our next tutorial, we will learn to set up struts 2 environment in eclipse.
     

    Read More