简体   繁体   English

如何在Spring MVC中从控制器访问bean?

[英]How to access bean from controller in Spring MVC?

I have bean 我有豆

<bean class="myprogram.FileList">

defined. 定义。

Now I wish this bean to be accessible from JSP. 现在我希望可以从JSP访问这个bean。 How to accomplish this? 怎么做到这一点?

First thought is to access bean somewhere in the controller method and put it to the model 首先想到的是在控制器方法中的某处访问bean并将其放入模型中

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    FileList fileList = // some code to access fileList bean

    model.addAttribute("fileList", fileList);

    return "home";
}

but probably this is ether not required or can be described somewhere in bean configuration? 但可能这是以太不是必需的,或者可以在bean配置中的某处描述?

UPDATE UPDATE

The answer is exposedContextBeanNames parameter. 答案是exposedContextBeanNames参数。

First of all, inject your bean into your controller using @Autowired annotation: 首先,使用@Autowired注释将bean注入控制器:

@Autowired
private FileList fileList;

Then add it into your model like you already did: model.addAttribute("fileList", fileList); 然后像你已经做的那样将它添加到模型中: model.addAttribute("fileList", fileList); .

In JSP use JSTL to access it. 在JSP中使用JSTL来访问它。 For eg: 例如:

Some property from File List bean: <c:out value="${fileList.someProperty}"/>

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

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