Mohamed Elalami
Mohamed Elalami

Reputation: 139

How to execute a method before execution of any action (check if a user has logged in) Struts 2

I want to check if the (session) user has logged in so if a user tried to reach a resource (a link) and he's not connected he must be redirected to login page, I could this verification

//when logging in
sessionMap.put("logined",true);

then

public String checkLogin() {
//when trying to reach a resource
if ((Boolean) sessionMap.get("logined")) return "Logined";
    else return "notLogined";
}

but I must execute this method in every method-action in class action and I must treat the result in every action on struts.xml.

so, my question is if there is a "light" solution using SessionAware and sessionMap:

    private SessionMap<String,Object> sessionMap;

I rather not using Spring Security.

Upvotes: 0

Views: 1372

Answers (1)

Roman C
Roman C

Reputation: 1

You can execute your method in the prepare(). To use this feature your action class should implement Preparable interface. Assumed that actions are configured to use defaultStack of interceptors which include this feature.

Prepare Interceptor:

This interceptor calls prepare() on actions which implement Preparable. This interceptor is very useful for any situation where you need to ensure some logic runs before the actual execute method runs.


If your logic is beyond the scope of the action class, then consider to use a custom interceptor for authentication. Here is an example of authentication interceptor.

Upvotes: 1

Related Questions