spring-mvcpostmodel-view-controllermodelattributerequest-mapping

Spring MVC : Passing string to backend


I want to ask the user, if they prefer pizza or sandwich, and I want to pass that to the backend. Here is my code:

<div id="food" class="modal">
    <div class="modal-content animate" >
        <div class="imgcontainer">
            <span onclick="document.getElementById('food').style.display='none'" class="close" title="Close Modal">&times;</span>
            
        </div>
        <form id="foodform" action="food" method="post">
            <input type="radio" id='pizza' name='pizza' value="pizza">
              <label > pizza </label>
              <input type="radio" id='burger'  name='burger' value="burger">
              <label > burger </label>
            <input type="submit" name="submitted" value="submit" />
        </form>
        </centre>
    </div>
  @RequestMapping(value = "/food", method = RequestMethod.POST)
        public String food(@Validated @ModelAttribute String food, Model model) {
            System.out.println(food);
            return "home";
        }
    

This is the controller code. But nothing is getting printed. Please help


Solution

  • Try something like this:

     @RequestMapping(value = "/food", method = RequestMethod.POST)
        public String food(HttpServletRequest request, @RequestParam String food){
             System.out.println(food);
             return "home";
        }