[ACCEPTED]-Sessions in struts2 application-struts2

Accepted answer
Score: 38

There are a few problems with the code you 19 currently have.

  • You should use an Interceptor to enforce that the user is logged in, rather than trying to enforce it in the JSP. JSP should only be for presentation, not for flow control.
  • You should avoid scriptlets (blocks of code) in JSP. That was deprecated a really long time ago and is widely considered to be a very poor practice in an MVC application.
  • You can access session values in your JSP directly. You do not need to implement the SessionAware interface in your action unless you need access to the session inside of the action itself.
  • You should redirect the user to a login action, not directly to a JSP page, otherwise you are bypassing the Struts2 framework and losing out on the benefits of using the framework.

Login Example

Below is some example code 18 for creating a basic login system using 17 the Struts2 framework.

Login Required

This part is optional, but 16 in general, not all pages in a web application 15 will require the user to be logged in. Therefore, let's 14 create an interface called LoginRequired. Any action 13 that implements this marker interface will 12 redirect to the login page if the user is 11 not already logged in.

Note: You can use 10 an annotation instead, if you prefer, but 9 for this example I will use the interface.

public interface LoginRequired {}

The Interceptor

The 8 interceptor will handle forcing the user 7 to login for any requested action which 6 implements the LoginRequired interface.

public class LoginInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(final ActionInvocation invocation) throws Exception {
        Map<String, Object> session = ActionContext.getContext().getSession();

        // sb: feel free to change this to some other type of an object which
        // represents that the user is logged in. for this example, I am using
        // an integer which would probably represent a primary key that I would
        // look the user up by with Hibernate or some other mechanism.
        Integer userId = (Integer) session.get("userId");

        // sb: if the user is already signed-in, then let the request through.
        if (userId != null) {
            return invocation.invoke();
        }

        Object action = invocation.getAction();

        // sb: if the action doesn't require sign-in, then let it through.
        if (!(action instanceof LoginRequired)) {
            return invocation.invoke();
        }

        // sb: if this request does require login and the current action is
        // not the login action, then redirect the user
        if (!(action instanceof LoginAction)) {
            return "loginRedirect";
        }

        // sb: they either requested the login page or are submitting their
        // login now, let it through
        return invocation.invoke();
    }
}

You will also 5 need a LoginAction which displays and processes the 4 login page and a LogoutAction which invalidates or clears 3 the session.

The Configuration

You will need to add the interceptor 2 to your stack and also create a global result 1 mapping for "loginRedirect".

<interceptors>
    <interceptor name="login" class="your.package.LoginInterceptor"/>

    <!-- sb: you need to configure all of your interceptors here. i'm only
         listing the one we created for this example. -->
    <interceptor-stack name="yourStack">
        ...
        <interceptor-ref name="login"/>
        ...
    </interceptor-stack>
</interceptors>

<global-results>
    <!-- sb: make this the path to your login action.
         this could also be a redirectAction type. -->
    <result name="loginRedirect" type="redirect">/login</url>
</global-results>
Score: 6

To maintain a session use SessionAware interface in 5 your action class and implement int public void setSession(Map m) it 4 will take the attribute as a key value pair 3 in map which can be be access from any 2 where just buy retrieving the key.

for example 1 Action class

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class LogingEx extends ActionSupport implements SessionAware{
    private static final long serialVersionUID = 1L;

    private String stuname,stuage,country;
    private int stumarks;
    Map m;

    public String getStuname() {
        return stuname;
    }
    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public String getStuage() {
        return stuage;
    }
    public void setStuage(String stuage) {
        this.stuage = stuage;
    }

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

    public int getStumarks() {
        return stumarks;
    }
    public void setStumarks(int stumarks) {
        this.stumarks = stumarks;
    }

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

    public String execute()
    {
        m.put("a",stuname);
        m.put("b", stuage);
        m.put("c",stumarks);
        m.put("d",country);

        return SUCCESS;
    }

}

SOURCE: http://www.java4s.com/struts-tutorials/example-on-struts-2-sessionaware-interface/

Score: 2

I find no reason to use this kind of Map to 11 authorize user. If your requirement is only 10 validate the user against session then I 9 would recommend to use Filter than some map in 8 some class, the problem with this kind of 7 map is to remove the session objects once 6 session is invalidated, of course you can 5 use HttpSessionListener to make it work but I guess it's best 4 to validate via Filter than Map.

Apart from it you 3 can take a look at many security framework 2 (like Apache Shiro) to make your task simpler and more 1 robust.

Score: 2

Has your Action class already implemented 6 the SessionAware interface?

EDIT:

Try this(It's a struts2 5 style solution):

public class anAction implements SessionAware{
    private Map<String, Object> session;
    public Map<String, Object> getSession() {
         return session;
    }
    public void setSession(Map<String, Object> session) {
         this.session = session;
    }
    public String getLoginStatus(){
         session.put("userName", "test");  //Hard code here for testing.
         return SUCCESS;
    }
}

Then use your jsp code to 4 get the userName on page. I've tested this 3 approach on my machine and it works.

EDIT2: BTW, such 2 login check can be done easily and elegant 1 with "Interceptor" provided by Struts2 Framework.

Score: 1

SessionAware implemention not required.

public class LoginAction extends Actionsupport
{
  private Map<String, Object> session;
  //Getter and Setter method
   public String execute() throws Exception {
      session=ActionContext.getContext().getSession();
      session.put("userName", "test");
     return super.execute();
   }
} 

0

Score: 0

Following journaldev article has more detail 2 in the same line of Steven response above 1 http://www.journaldev.com/2210/struts-2-interceptor-tutorial-with-custom-authentication-interceptor-example

More Related questions