访问Spring MVC DI bean从jsp [英] Accessing Spring MVC DI beans from jsp

查看:125
本文介绍了访问Spring MVC DI bean从jsp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些MVC框架中,如果您希望执行一些代码并渲染一些局部视图,您可以从视图调用控制器操作。我不知道什么是在Spring MVC中的正确方法



我想有一组JSP模板。其中一些将是页面布局,其中一些将是小组件,如分页器,登录框,菜单,标签云等等等。每个组件都需要一些bean或控制器动作来设置一些数据到ViewAndModel,以便视图可以使用它。



问题是我不想在每次调用中设置所有这些对象。我的寄存器控制器只关心注册处理。所以现在我怎么做呢?如何从视图调用DI bean或控制器以准备部分视图?还是应该创建一些映射?

$ p

解决方案

Spring-MVC可以将应用程序上下文的bean暴露给视图层,如果这是你想要做的。



例如,可以指示 InternalResourceViewResolver 上下文,或只是指定的。请查看 exposeContextBeansAsAttributes exposedContextBeanNames 属性。



例如,将bean beanA beanB 暴露给您的JSP。您将在上下文中声明视图解析器:

 < bean class =org.springframework.web.servlet.view .InternalResourceViewResolver> 
< property name =exposedContextBeanNames>
< list>
< value> beanA< / value>
< value> beanB< / value>
< / list>
< / property>
< / bean>

或者,为了公开每个bean:

 < bean class =org.springframework.web.servlet.view.InternalResourceViewResolver> 
< property name =exposeContextBeansAsAttributesvalue =true/>
< / bean>

这是否是一个好主意是另一个问题,但Spring会给你的选择。 / p>

In some MVC frameworks you can call controller action from the view if you wish to execute some code and render some partial view. I'm not sure what is the correct way to do it in Spring MVC

I want to have set of JSP templates. Some of them will be page layouts some of them will be small components like paginator, login box, menu, tag cloud etc etc etc. Each of these component need some beans or controller action to set some data into ViewAndModel so that view could use it.

The problem is I don't want to set all these objects in each call. My register controller cares only about registration processing. So now how do i do it right? How do I call DI beans or controllers from the view to prepare partial views? Or should I create some mappings? Or am I approaching the problem from totally wrong angle?

解决方案

Spring-MVC can expose the application context's beans to the view layer, if that is what you wish to do.

For example, the InternalResourceViewResolver can be instructed to expose every bean in the context, or just specified ones. Take a look at the exposeContextBeansAsAttributes and exposedContextBeanNames properties.

For example, say you wanted to expose the beans beanA and beanB to your JSPs. You would declare the view resolver in your context thus:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="exposedContextBeanNames">
      <list>
         <value>beanA</value>
         <value>beanB</value>
      </list>
   </property>
</bean>

Alternatively, to just expose every bean:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="exposeContextBeansAsAttributes" value="true"/>
</bean>

Whether or not this is a good idea is another question, but Spring does give you the option.

这篇关于访问Spring MVC DI bean从jsp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆