Suzan Cioc
Suzan Cioc

Reputation: 30097

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.

Upvotes: 0

Views: 3987

Answers (1)

Paulius Matulionis
Paulius Matulionis

Reputation: 23415

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 e.g:

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

Upvotes: 2

Related Questions