简体   繁体   中英

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. How to accomplish this?

First thought is to access bean somewhere in the controller method and put it to the model

@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?

UPDATE

The answer is exposedContextBeanNames parameter.

First of all, inject your bean into your controller using @Autowired annotation:

@Autowired
private FileList fileList;

Then add it into your model like you already did: model.addAttribute("fileList", fileList); .

In JSP use JSTL to access it. For eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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