4

I am new to Spring MVC (coming from Grails). Is it possible to use a HashMap as a form backing bean?

In Grails, one has access to an object called params from any controller action. Params is simply a map that contains the values of all the fields included in the POSTed data. From what I have read so far, I have to create a form backing bean for all of my forms.

Is using Maps as the backing object possible?

jett
  • 947
  • 9
  • 27

1 Answers1

5

You don't need to use form backing object for this. If you just want to access parameters that is passed in request (e.g. POST, GET ...) you need to get parameters map with HttpServletRequest#getParameterMap method. Look at example example that prints all parameters name and value to console.

On the other hand. If you want to use binding you can wrap Map object into form backing bean.

Controller

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ParameterMapController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String render() {
        return "main.html";
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String submit(HttpServletRequest req) {
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Entry<String, String[]> entry : parameterMap.entrySet()) {
            System.out.println(entry.getKey() + " = " + Arrays.toString(entry.getValue()));
        }

        return "redirect:/";
    }
}

main.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
</head>
<body>

<form th:action="@{/}" method="post">
    <label for="value1">Value 1</label>
    <input type="text" name="value1" />

    <label for="value2">Value 2</label>
    <input type="text" name="value2" />

    <label for="value3">Value 3</label>
    <input type="text" name="value3" />

    <input type="submit" value="submit" />
</form>

</body>
</html>
michal.kreuzman
  • 12,170
  • 10
  • 58
  • 70
  • @michal.kreuzman can you please help me on my question i am not able to bind map in jsp tag please see my post for more elaboration http://stackoverflow.com/questions/30679449/forminput-tag-in-jsp-is-not-converting-to-input-tag-of-html-for-map-property – henrycharles Jun 06 '15 at 07:44