Abhishek Singh
Abhishek Singh

Reputation: 9729

Spring MVC use application scope level attribute instead of session scope level attribute

In Spring MVC we can use

@SessionAttributes("variable")

and

model.addAttribute("variable", new Object());

Such that this variable once set is availabel to user session.

Now i want this variable to be set at application scope such that if user 1 sets this attribute it will be available to all my users user 2, user 3, user 4 etc.

and this variable will be used on my jsp page. Please suggest.

Upvotes: 1

Views: 4228

Answers (2)

Dani
Dani

Reputation: 4111

You can define one simple Pojo as Spring Bean Service to do.

@Service
public class MyVariable{

    private Object myVar;

    public Object getMyVar() {
        return myVar;
    }

    public void setMyVar(Object myVar) {
        this.myVar = myVar;
    }

}

Then, you can @Autowired this service in your @Controller and get it to anything.

Upvotes: 3

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279890

If you mean web application scope, then you need to set it in the ServletContext attributes. Because this isn't a common thing to do in web applications from a user perspective, Spring doesn't offer a shortcut. Instead, just retrieve the ServletContext either by injecting it into your @Controller or providing it as a parameter to a handler method and add the attribute

ServletContext ctx = ...;
ctx.setAttribute("name", new Object());

Note that there is a single ServletContext per web application. The ServletContext does not guarantee any atomicity, ie. it is not synchronized. You need to do that synchronization yourself, if required by the application.

Upvotes: 3

Related Questions