从 jsp 访问 Spring MVC DI bean

编程入门 行业动态 更新时间:2024-10-27 10:34:30
本文介绍了从 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.看看 exposeContextBeansAsAttributes 和 exposedContextBeanNames 属性.

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 beanA 和 beanB 公开给您的 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

本文发布于:2023-11-16 21:50:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Spring   jsp   MVC   bean   DI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!