Anish
Anish

Reputation: 255

Accessing ServletContext object in Action class in Struts 1.2

I have been given a use-case, to come up with a solution to allow configured number of users per user id to be logged in to my application at any given time. For example : userid 'parentuser' can be used to log in to the application for a max of 10 times at any time.After this limit, the user will not allowed to log in as max number of users are accessing the application for that user. Now, To implement this, I have created a context listener which will instantiate an attribute which I'll keep updating as the user logs in the application in the Action class. My Context Listener is as under :

public class ApplicationContextListener implements ServletContextListener {

private Map<String, List<ApplicationContextBean>> userMap;

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    userMap = null;
}

@Override
public void contextInitialized(ServletContextEvent event) {
    userMap = new HashMap<String, List<ApplicationContextBean>>();
}

public Map<String, List<ApplicationContextBean>> getUserMap() {
    return userMap;
}

public void setUserMap(Map<String, List<ApplicationContextBean>> userMap) {
    this.userMap = userMap;
}

}

web.xml is as under

<listener>
    <listener-class>com.pcs.bpems.portal.listener.ApplicationContextListener</listener-class>
</listener>

Question : How can I now access this context object 'userMap' from my action class? If anyone has any other approach different than this also, kindly post the same. Thanks

Upvotes: 1

Views: 1373

Answers (2)

Anish
Anish

Reputation: 255

This can be stored in the Servlet Context as under :

@Override
public void contextInitialized(ServletContextEvent event) {
    userMap = new HashMap<String, Map<String,List<ApplicationContextBean>>>();
    event.getServletContext().setAttribute(ApplicationConstants.LOGGED_IN_USERS, userMap);
}

The stored parameters can be then fetched from the HttpSession Object as under :

currentSession.getServletContext().getAttribute(LOGGED_IN_USERS)

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

The answer is in the title of your question: store the Map (or an object wrapping the map and providing useful methods) into an attribute of the servlet context (accessible from the event), and retrieve it from wherever you want: the HttpServletRequest provides access to the servlet context.

A better solution, which would also work in case your application is clustered, would be to use the database.

Also, don't forget to decrement the counter when the session expires.

Upvotes: 2

Related Questions