user1759136
user1759136

Reputation:

Spring MVC pass a list of values into controller from JSP page

If I have a HTML in a <form> like this:

    <input type="text" value="someValue1" name="myValues"/>
    <input type="text" value="someValue2" name="myValues"/>
    <input type="text" value="someValue3" name="myValues"/>
    <input type="text" value="someValue4" name="myValues"/>

I know that in servlets I am able to get values using:

String[] values = request.getParameterValues("myValues");

How can I do something similar using Spring MVC?

Upvotes: 6

Views: 21199

Answers (3)

Dalton Dias
Dalton Dias

Reputation: 76

In jsp i would like:

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!-- Add taglib in beginning of the page.-->

<!-- In body the html -->
<form:form  action="/foo" method="post" commandName="MyValues">
  <input type="text" value="someValue1" name="myValues1"/>
  <input type="text" value="someValue2" name="myValues2"/>
  <input type="text" value="someValue3" name="myValues3"/>
  <input type="text" value="someValue4" name="myValues4"/>
</form:form>

See references in section 13.9. Using Spring's form tag library tag explains, in link: http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html

The controller is part of the same friend Alex answered.

Upvotes: 0

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

You already have HttpServletRequest request in spring web MVC. We can get it using the same i.e. using

 String[] values = request.getParameterValues("myValues");

Also you can use ServletRequestUtils to read request parameters in Spring like :

String[] values = ServletRequestUtils.getRequiredStringParameters(request, "myValues");

See how to access Http request : Spring 3 MVC accessing HttpRequest from controller

For annotation based approach: See Alex's answer.

Upvotes: 2

Alex
Alex

Reputation: 25613

The parameters are passed as arguments to the method bound to your controller

@RequestMapping(value = "/foo", method = RequestMethod.POST) // or GET
public String foo(@RequestParam("myValues") String[] myValues) {
    // Processing
    return "view";
}

Upvotes: 7

Related Questions