Struts 2 Interceptor Example
Posted on: February 17, 2011 at 12:00 AM
In this tutorial you will learn about the struts interceptors and how to map it in struts.xml

Struts 2 Interceptor Example

Interceptor is an object which intercepts an action dynamically. It executed before and after the action execution. It Allows the developers to write a code which can execute and after the action. It executed before and after the code. It can prevent an action before executing.

The mapping of interceptor is done as follows

<interceptors>
	<interceptor name="Name Of the Interceptor"
	class="interceptor class path with full package " />
	<interceptor name="Name Of the 2nd Interceptor"
	class="interceptor class path with full package " />
</interceptors>

Mapping Interceptor for an action
<action name="actionName" class="actionClass">
	<interceptor-ref name="defaultStack">
		<param name="validation.excludeMethods">MyValidationMethod</param> 
	</interceptor-ref>
</action>

Consider an example of Struts interceptor given bellowADS_TO_REPLACE_1

Login.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<head>
<title>Login Page</title>
</head>
<body bgcolor="lightblue">
<s:head/>
<br>
<center><h2><u>Please Login</u></h2></center>
<s:form action="doLogin">
<table border=0 align="center">
<tr>
<td><s:textfield name="userName"
label="User Name" /></td>
</tr>
<tr>
<td><s:submit align="center" value="login" /></td>
</tr>
</table>
</s:form>
</body>

Welcome.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<%@page import="javax.xml.crypto.Data"%>
<%@page import="java.util.Date"%><html>
<head>
<title>Welcome</title>
<link href="<s:url value="/css/examplecss"/>" rel="stylesheet"
type="text/css"/>
</head>

<body>
<h1 align="center">You Are Welcome</h1>
</body>
</html>

error.jspADS_TO_REPLACE_2

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h2>Error Page</h2>
Go to <a href="<s:url action="loginPage"></s:url>">Login</a>
</body>
</html>

LoginModel.java

package net.roseindia.model;

import java.io.Serializable;


public class LoginModel implements Serializable{
	private static final long serialVersionUID = -5995468832791791552L;

	private String userName;

	public String getUserName() {
		return userName;
	}

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

MyLoginInterCeptor.java

package net.roseindia.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.roseindia.model.LoginModel;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyLoginInterCeptor implements Interceptor {
	private static final long serialVersionUID = 1L;

	String result = null;
	String className = null;
	long startingTime = 0;
	long endingTime = 0;
	final HttpServletRequest request = (HttpServletRequest) ActionContext
			.getContext().get(ServletActionContext.HTTP_REQUEST);
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("Destroying Interceptor");

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		System.out.println("Intialising Interceptor");

	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		className = invocation.getAction().getClass().getName();
		startingTime = System.currentTimeMillis();
		System.out
				.println("Interceptor Starting Time" + new Date(startingTime));
		result = invocation.invoke();
		System.out.println(result);

		endingTime = System.currentTimeMillis();
		System.out.println("Interceptor Enging Time " + new Date(endingTime));
		System.out.println("Time Taken by the Interceptor "
				+ new Date(endingTime - startingTime));
		return result;

	}
	
}

LoginAction.javaADS_TO_REPLACE_3

package net.roseindia.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.roseindia.model.LoginModel;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	ActionContext context = ActionContext.getContext();
	HttpServletRequest request = (HttpServletRequest) context
			.get(ServletActionContext.HTTP_REQUEST);
	HttpSession session;

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
}

LoginAction-validation.xml

<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
<field name="userName">
<field-validator type="requiredstring">
<message key="requiredstring" />
</field-validator>
</field>

<field name="password">
<field-validator type="requiredstring">
<message key="requiredstring" />
</field-validator>
</field>

</validators>

LoginAction.properties

userName = User Name
password = Password
requiredstring = ${getText(fieldName)} is Required

struts.xmlADS_TO_REPLACE_4

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />

<package name="roseindia" namespace="/" extends="struts-default">

<interceptors>
<interceptor name="loginInterceptor"
class="net.roseindia.interceptor.MyLoginInterCeptor" />
</interceptors>

<global-results>
<result name="error" type="freemarker">/resources/Login.jsp</result>
</global-results>

<action name="loginPage" method="displayForm" class="net.roseindia.model.LoginModel">
<result name="input">/resources/Login.jsp</result>
</action>

<action name="doLogin" class="net.roseindia.action.LoginAction">
<interceptor-ref name="loginInterceptor"/>
<interceptor-ref name="logger" />
<result name="success">/resources/Welcome.jsp</result>
<result name="input">/resources/Login.jsp</result>
<result name="error">/resources/error.jsp</result>
</action>

</package>

</struts>


When you run this application it will display message as shown below:


 

Download Select Source Code

Related Tags for Struts 2 Interceptor Example :

Advertisements

Ads

 
Advertisement null

Ads