Pages Navigation Menu

Coding is much easier than you think

Login Interceptor in Struts 2

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 :

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 {

	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String, Object> session = invocation.getInvocationContext().getSession();

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

		if (loginId == null) 
			return Action.LOGIN;
			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.

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<String, Object> session;

	public String home() {
		return SUCCESS;

	// Log Out user
	public String logOut() {
		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<String, Object> getSession() {
		return session;

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

	public void setSession(Map<String, Object> 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.

<package name="default" extends="struts-default">
		<interceptor class="com.interceptor.LoginInterceptor" name="loginInterceptor">
		<interceptor-stack name="loginStack">
			<interceptor-ref name="loginInterceptor" />
			<interceptor-ref name="defaultStack" />

	<!-- login action -->
	<action name="loginUser" class="com.action.LoginAction" method="login">
		<result name="success" type="redirect">homeAction</result>
		<result name="login">login.jsp</result>

	<!-- home link action -->
	<action name="homeAction" class="com.action.LoginAction" method="home">
		<interceptor-ref name="loginStack" />
		<result name="login">login.jsp</result>
		<result name="success">home.jsp</result>
	<!-- logout action -->
	<action name="logOut" class="com.action.LoginAction" method="logOut">



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




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

About Mohaideen Jamil

Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • Himanshu Parmar

    i have a problem while uploading a image in struts-2 and not retrive that image from database please
    guide me

  • Zakvan Mansuri

    Thank you for this very easily understandable example.

  • hareesh

    thanks for example

    • User

      I created a SessionInterceptor that checks whether the user information is present in session and session is expired or not. If the session is null or empty then I want to return the control to Login page. But the problem is when I enter username and password and click submit button it goes to the session interceptor class, it says session is null or return to login page again, even after entering correct username and password.
      //Session Intrceptor
      public class SessionInterceptor extends AbstractInterceptor {
      public String intercept(ActionInvocation invocation) throws Exception {
      Map session = invocation.getInvocationContext().getSession();
      System.out.println("Checking ssession");
      if(session.get("firstName") == null) {
      System.out.println("Your session has expired.");
      return "invalidSession";
      return invocation.invoke();
      How would session will be created if the user does not logged in, as it redirects me before logging in the user.

      • Mohaideen Jamil


        Just don’t include your interceptor in login Action class mapping.


        <action name=”loginUser” class=”com.action.LoginAction” method=”login”>
        <result name=”success” type=”redirect”>homeAction
        <result name=”login”>login.jsp

        This ensures that your session interceptor is not triggered when ever login action is called.

        And for rest of the action class where ever you need to check logged in user name, then there alone add your session interceptor as shown below.

        <action name=”homeAction” class=”com.action.LoginAction” method=”home”>
        <interceptor-ref name=”loginStack” />
        <result name=”login”>login.jsp
        <result name=”success”>home.jsp

        Please refer to the above post completely.

        Apologies – Code tag is not working properly for xml code.

        • User

          Hi, I tried using your code. User is getting logged in but, it is throwing error when I dont write result type = input in homeAction.


          If I write above code then I am getting following error. No result defined for action com.action.LoginAction and result input. So I tried using below:


          The user is getting logged in but, it returns to Login page saying that your password and email can not left blank. As should redirect to Welcome page.

          Any suggestioin.

        • uday

          session.put(“loginId”, username);—–this line having unhandled exception.