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

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

问题描述

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

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

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

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.

问题是我不想在每次调用中设置所有这些对象.我的注册控制器只关心注册处理.那么现在我该怎么做呢?如何从视图中调用 DI bean 或控制器来准备局部视图?或者我应该创建一些映射?还是我从完全错误的角度处理问题?

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 可以将应用程序上下文的 bean 暴露给视图层,如果这是您希望做的.

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

例如,可以指示 InternalResourceViewResolver 公开上下文中的每个 bean,或仅公开指定的 bean.看看 exposeContextBeansAsAttributesexposedContextBeanNames 属性.

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.

例如,假设您想将 bean beanAbeanB 公开给您的 JSP.您将在您的上下文中声明视图解析器:

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>

或者,只公开每个 bean:

Alternatively, to just expose every bean:

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

这是否是一个好主意是另一个问题,但 Spring 确实为您提供了选择.

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

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

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