Alex Dowining
Alex Dowining

Reputation: 970

JSP get/post with Spring MVC

I'm trying to create a registration form. In this form there are some fields(username,password etc) and also a dropdown listbox. My problem is with this listbox.I manage to retrieve succesfully from a server all the items that will be added in the listbox and i want know to put it in this form.

More specific i have a list called lista, which contains the items i want to add in the listbox.

JSP:

<c:url var="attinto" value="/reg" />
<form:form modelAttribute="attribute" method="POST" action="${attinto}">
<table>
    .
            .

    <tr>
        <td><form:label path="researchareas">Research area:</form:label></td>
        <td>    
          <select multiple="multiple">   
            <c:forEach items="${researchareas}" var="researcharea">     
              <option value="${researcharea}">  ${researcharea} </option>                   
            </c:forEach>
          </select>    
        </td> 
    </tr>

Controller:

    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public String getform(Model model) {

        getAll(model);
        model.addAttribute("attribute", new Reg());

        return "reg";
    }

I have to mention at this point that the getAll(model) is a void method similar to the following:

      model.addAttribute("researchareas",lista);

Then i create a POST method to send this data.

Question:How can i add in the form the data from the list(into a listbox)?How i can take back the values that the user will select?

Upvotes: 1

Views: 4200

Answers (2)

Japan Trivedi
Japan Trivedi

Reputation: 4483

Please specify post method in your form in jsp and also in controller specify method=RequestMethod.POST.

One more thing.

There should not be the list as your data type for researchareas in your Registration class. Try giving the datatype as String[]

Hope this works for you. Cheers.

Upvotes: 2

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

First of all, use form:select like this:

<form:select path="researchareas" items="${researchareas}" multiple="true" />

Then Spring could automatically bind corresponding attribute in Registration object:

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String getRegistrationForm( //
    @ModelAttribute("registrationAttribute") Registration registration, //
    BindingResult result, Model model) {
  ...
  return ...
}

Assuming Registration class has the following:

public class Registration {
  String username;
  String password;
  List<String> researchareas;

  ... corresponding getters and setters here
}

Though I'd name attribute the same as class or else you'd have to specify explicit names in the method parameters annotations.

Upvotes: 2

Related Questions