1

I am creating a web application using Struts 2. I have a login page in it. As the user click the login button after entering the username and password, the credentials are checked and if the credentials are found correct, then a session is created and its attributes are set and control is redirected to WELCOME JSP.

Now before the welcome.jsp is opened, I want to check, if the session attributes are set. How to do it in Struts 2?

Can anyone clear me the concept of interceptors. I read that we create interceptors to perform any function before or after an action is called. Can I create an interceptor that checks if the session is set, every time before WELCOME JSP is called.

Roman C
  • 49,761
  • 33
  • 66
  • 176

4 Answers4

5

you can use <s:if> tag to test presence of your attribute in Session.I am assuming that you are setting value in your action class and here is how you can do that in jsp page

<s:if test="%{#session.logged_in ==true}">

I am assuming that here i am setting a flag indicating if user is logged in or not on similar way you can test as per your requirements

For Interceptors, They are set of utility classes being provided by Struts2 out of the box to make your life easy.Interceptors are just java classes with certain functionality which is being provide by the framework, some of them are

  1. fileUpload
  2. i18n
  3. params
  4. token etc

These Interceptors are called based on the interceptor stack being configured in your application and they will be called at 2 places

  1. when you send request to your action
  2. when request processing done and view rendered.

in first case they will be called before your action execute or custom method defined by you is called, Interceptors are responsible to provide required data to your action class, some of the work done by interceptors before your action called are

  1. File uploading
  2. Handling i18n
  3. Passing form values to respected fields in your action class
  4. validation of your data

there are certain set of interceptors being provided by struts2 , you can have look at struts-defaultxml.

You can create any number of interceptors and configure them to be executed as per your requirements,a ll you need to extends AbstractInterceptor an provide your custom logic inside intercept(ActionInvocation invocation) method I suggest you to follow below mentioned links to get more overview

building-your-own-interceptor Struts2 Interceptors writing-interceptors

Umesh Awasthi
  • 23,407
  • 37
  • 132
  • 204
3

@rickgaurav for your 1st question. make a login action like this

<action name="login_action" class="loginAction class">
            <result name="success" type="chain">welcomeAction</result>
            <result name="input">/index.jsp</result>
            <result name="error">/index.jsp</result>
        </action>

wher index.jsp is your login page

and in login interceptor first make a session map in which your session attribute will be store

Map<String, Object> sessionAttributes = invocation
            .getInvocationContext().getSession();

after that check using this condition

if (sessionAttributes == null
                || sessionAttributes.get("userName") == null
                || sessionAttributes.get("userName").equals("")) {

            return "login";
        }else{
if (!((String) sessionAttributes.get("userName")).equals(null)){
return invocation.invoke();
}else{
return "login";
}

for your 2nd question assume you are calling a welcomeAction to go to the welcome.jsp page so you can add action like this

<action name="welcomeAction" class="class">
        <interceptor-ref name="logininterceptor"></interceptor-ref>




            <result name="login" type="chain">loginaction</result>
        <result name="success" >/welcome.jsp</result>

    </action>

hope so this will work for you

Pratik Shah
  • 1,782
  • 1
  • 15
  • 33
  • What should i write in the execute method of the action class corresponding to action "welcomeaction". –  Sep 06 '13 at 06:00
  • Inside the execute method of welcomeaction class, i simply returned success. Now when i try to login with the correct credentials, it shows an error saying INFINITE RECURSION DETECTED. loginAction...Welcomeaction...loginAcction..... Any improvements i should apply? –  Sep 06 '13 at 06:16
  • @rickgaurav can you show me your struts.xml file??? – Pratik Shah Sep 06 '13 at 09:18
  • hey just remove line from your "login" action. – Pratik Shah Sep 06 '13 at 09:51
  • I removed that line from login action. –  Sep 06 '13 at 10:20
  • i am done with all . Only problem left is when user directly hit the welcome url. –  Sep 06 '13 at 10:34
  • for a good practice you don't have to call any pages directly. just call it using action. so you can check wether user is logedin or not using the interceptor. – Pratik Shah Sep 06 '13 at 11:23
2
  1. In Struts.xml write this:

    <interceptors> <interceptor name="loginInterceptor" class="com.mtdc.interceptor.LoginInterceptor"></interceptor> <interceptor-stack name="loginStack"> <interceptor-ref name="loginInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>

2.Now After aAction which you want to check session put this: <interceptor-ref name="loginStack"></interceptor-ref>

3.Our LoginACtion in struts.xml: `

<action name="login_action" class="com.action.LoginAction">

      <result name="success">/welcome.jsp</result>
      <result name="input">/login.jsp</result>
      <result name="error">/login.jsp</result> 

  </action>

`

4.Now define LOgin interceptor for that make com,interceptor.LoginInterceptor :

`

    public String intercept(ActionInvocation invocation) throws Exception {

            Map<String, Object> sessionAttributes = invocation
                    .getInvocationContext().getSession();
            if (sessionAttributes == null
                    || sessionAttributes.get("userName") == null
                    || sessionAttributes.get("userName").equals("")) {

                return "login";
            } else {

                if (!((String) sessionAttributes.get("userName")).equals(null)
                        || !((String) sessionAttributes.get("userName")).equals("")) {

                    return invocation.invoke();
                } else {

                    return "login";
                }
            }
        }

`

[5]. Now make Login Action class where you assign session:

` 

    public String execute() {

        String result = LOGIN;
        UserLogin userlogin;
        try {
            userlogin = userlogindao.authenticateUser(signin_username, signin_password);
            if (userlogin != null && userlogin.getUsername() != null) {

            session.put("userID", userlogin.getUserId());
            session.put("userName", userlogin.getUsername());


            result = SUCCESS;
            } else {

            result = LOGIN;
            }
        } catch (Exception e) {
            result = LOGIN;


            e.printStackTrace();
        }
        return result;
        }

`

[6]. Now final step on your login page on click call action LoginAction.

Jay Trivedi
  • 170
  • 1
  • 1
  • 10
  • Thanks for the answer. Can you please explain , what each of the if condition in your interceptor code do? –  Sep 05 '13 at 12:36
  • In 1st 'If' it checks is there session attribute null? If "yes" then it give return "login" and it will redirect you to login page. and 1st "If" false then go to else there it checks session attribute is not equal to null and if its true then invocation invoke means our action in which we put interceptor will invoke. Yeah you can edit this logic by only one if..else.... Are you clear? – Jay Trivedi Sep 06 '13 at 04:50
0

Yes you can use interceptor. Make a Action class Which will store UserId / Username of user (after user is authenticated) in session like this.

session.put("userID", userlogin.getUserId());

after that make a Interceptor class which impl. interceptor

public class LoginInterceptor implements **Interceptor** {  

public String intercept(ActionInvocation invocation) throws Exception {

get the session attribute using

sessionAttributes.get("userId");

and check it is not null if it is null then return login to forward user to the login page or else return invocation.invoke(); to continue the action.

and in struts.xml file configure interceptor inside package

<interceptors>
            <interceptor name="loginInterceptor" class=".....LoginInterceptor"></interceptor>
            <interceptor-stack name="loginStack">
                <interceptor-ref name="loginInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>

and for action you can write

<action name="anything" class="anyclass" method="default">
            <interceptor-ref name="loginStack"></interceptor-ref>

    <result name="login">/index.jsp</result>

            <result name="success" type="redirect">success.jsp</result>

    </action>
Pratik Shah
  • 1,782
  • 1
  • 15
  • 33
  • No need of implementing interceptor for this small stuff. – Shailesh Saxena Sep 04 '13 at 11:58
  • @prtk_shah Thanks for the answer. I tried, what you answered. The problem is ,as soon as i enter my login credentials, interceptor is called and checks if the sessionattribute userid is set which obviously will be null since we haven't checked the credentials yet. I want a solution which call the interceptor only after my credentials are checked i.e. after my action has been called. And can u please tell me what will happen if i directly open the welcome page jsp by writing its url? Can i do anything that redirect the user to login page in this case also? –  Sep 04 '13 at 12:05