Batman
Batman

Reputation: 928

Display value in JSP using Spring TagLibs

Is there a way to show the values already populated in a bean using Spring Tag Libraries? I know that we can use the ${} notation to see the values. I'm trying to do something like the following:

<form:form commandName="studentBean" method="POST">
<form:input path="fName"></form:label>
</form:form>

This is ok if I want to update the values, but it won't show the values already present in the commandBean. Can anybody post a solution for that?

Upvotes: 0

Views: 831

Answers (1)

Ralph
Ralph

Reputation: 120771

It should work this way. The (form (xmlns:form="http://www.springframework.org/tags/form")) input field should be prepopulated with the values you put in the command object in the controller in which result the jsp page is rendered.

May you missed to populate the model.

@RequestMapping(value = "/xxx", params = "form", method = RequestMethod.GET)
public ModelAndView updateForm() {
    ...
    StudentBean studentBean = new StudentBean();
    studentBean.setFName("Ralph");
    return new ModelAndView("updateForm", "studentBean", studendBean);
}

@RequestMapping(value = "/xxx", method = RequestMethod.POST)
public ModelAndView update(@Valid StudentBean studentBean,
                           final BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return new ModelAndView("updateForm", "studentBean", studendBean);
    } else {
        ...
        return new ModelAndView(new RedirectView("/finished", true));
    }
}

So in the end you need two methods, one to populate the form/command/bean initial, and a second to handle the user input.

BTW: The term "Bean" is very uncommon to that kind of object used to populate the form and containing the request. (In JSF it is called (Managed)Bean, but you using JSP (this is command base, not comparable with the component based JSF). It is also not a Spring-Bean, because it is not a spring managed object. -- I personally us the term "command" for that kind object. (accordign to the spring reference: 15.3.2.3 Supported handler method arguments and return types "Command or form objects to bind parameters to:...")

Upvotes: 1

Related Questions