How to add an object to application scope in Spring

后端 未结 3 1568
长情又很酷
长情又很酷 2021-02-14 10:06

We can set the request attributes using Model or ModelAndView object in Spring.

We can use @SessionAttributes to keep attributes

3条回答
  •  故里飘歌
    2021-02-14 10:31

    When you mention about storing your model at application scope then I would conclude you wish to store it at the ServletContext level. For doing that you need to make your controller implements ServletContextAware interface.

    import org.springframework.web.context.ServletContextAware;
    
    // ...
    
    public class MyController implements ServletContextAware {
    
    private ServletContext context; 
        public void setServletContext(ServletContext servletContext) { 
        this.context = servletContext;
         }
    

    After getting access to ServletContext you can add it as a attribute

    servletContext.setAttribute("modelKey", modelObject);
    

    Kindly let me know if this is what you are looking for.

提交回复
热议问题