简体   繁体   中英

Spring-MVC with JSP. How to access a singleton-scoped object from a JSP page?

Got a custom formatter bean in a singleton scope. And want to use it in a JSP page.

First way:

  • @Autowired (or @Inject) the bean in a controller
  • put the bean in the JSP context

==Code==

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView get() {
        ModelAndView result = new ModelAndView( "view" );
        result.addObject( "format", format );
        return result;
    }

The simpliest way, but when this bean is needed in almost every page, it hurts.

Second way:

  • move the bean to session-scope
  • @Autowired (or @Inject) the bean in a controller
  • now the bean is stored in the session and we can find it in sessionScope

==Code==

<div>
${sessionScope.format.doSmth()}
</div>

Bad way too. First, need to inject the bean - the bean is created only when it's injected by Spring Context. Otherwise the bean won't be created and put into the session. Second, my IDE (IDEA) doesn't provide syntax highlighting in that case.

So the question is:

Is there any way to use a singleton-scoped bean in a JSP page without putting it in context every time and with IDE support?

I would think about 2 ways of making a (singleton scoped) bean disponible in JSP view.

  • store it as a ServletContext attribute. Any bean (including @Configuration beans of the formatter bean itself) can to that in a init-method . It is then immediately accessible through EL to all JSP
  • use an interceptor to put it in model after all or some controllers. It is available for only those views, but it will still work if you later decide to use other view like Velocity or Thymeleaf

But I really have no idea how to get IDE support :-( (don't use IDEA)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM