简体   繁体   English

具有JSP的Spring-MVC。 如何从JSP页面访问范围单一的对象?

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

Got a custom formatter bean in a singleton scope. 在单例作用域中获得了一个自定义格式化程序bean。 And want to use it in a JSP page. 并希望在JSP页面中使用它。

First way: 第一种方式:

  • @Autowired (or @Inject) the bean in a controller @Autowired(或@Inject)控制器中的bean
  • put the bean in the JSP context 将bean放在JSP上下文中

==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. 最简单的方法,但是当几乎每个页面都需要此bean时,它很痛苦。

Second way: 第二种方式:

  • move the bean to session-scope 将bean移到session-scope
  • @Autowired (or @Inject) the bean in a controller @Autowired(或@Inject)控制器中的bean
  • now the bean is stored in the session and we can find it in sessionScope 现在,bean存储在会话中,我们可以在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. 首先,需要注入bean-仅当Spring Context注入bean时才创建。 Otherwise the bean won't be created and put into the session. 否则,将不会创建Bean并将其放入会话中。 Second, my IDE (IDEA) doesn't provide syntax highlighting in that case. 其次,在这种情况下,我的IDE(IDEA)不提供语法突出显示功能。

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? 有什么方法可以在JSP页面中使用单例作用域的bean,而不必每次都将其置于上下文中并获得IDE支持吗?

I would think about 2 ways of making a (singleton scoped) bean disponible in JSP view. 我会考虑两种在JSP视图中使(单作用域)bean不负责任的方法。

  • store it as a ServletContext attribute. 将其存储为ServletContext属性。 Any bean (including @Configuration beans of the formatter bean itself) can to that in a init-method . 任何bean(包括formatter bean本身的@Configuration bean)都可以使用init-method中的bean。 It is then immediately accessible through EL to all JSP 然后可以通过EL立即将其访问所有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 它仅适用于那些视图,但是如果您以后决定使用其他视图(例如Velocity或Thymeleaf),它将仍然有效

But I really have no idea how to get IDE support :-( (don't use IDEA) 但是我真的不知道如何获得IDE支持:-((不要使用IDEA)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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