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

时间:2013-05-03 11:32:29

标签: java spring jsp spring-mvc javabeans

我有豆

<bean class="myprogram.FileList">

定义。

现在我希望可以从JSP访问这个bean。如何做到这一点?

首先想到的是在控制器方法中的某处访问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";
}

但是这可能是不需要的ether,或者可以在bean配置中的某处描述?

更新

答案是exposedContextBeanNames参数。

1 个答案:

答案 0 :(得分:2)

首先,使用@Autowired注释将bean注入控制器:

@Autowired
private FileList fileList;

然后将其添加到您的模型中,就像您已经做过的那样:model.addAttribute("fileList", fileList);

在JSP中使用JSTL来访问它。例如:

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