Spring – href with multiple parameters spring

parametersspringurl

i want to sent 3 params to the controller with the following:

<li><a href="result?name1=thor&name2=hulk&name3=loki">SMTH</a></li>

the controller:

@Controller
@RequestMapping(value="/result")
public class SmthController {

    @RequestMapping(method=RequestMethod.GET)
    public String dosmth(HttpServletRequest request) {

        String one = request.getParameter("name1");
        String two = request.getParameter("name2");
        String three = request.getParameter("name3");


        JOptionPane.showMessageDialog(null,
                " Param 1 is:" +one +" \n Param 2 is: " +two +" \n Param 3 is: " +three);

        return "redirect:/";
    }
}

Best Answer

Your code is OK, but this is the Spring-way:

@Controller
@RequestMapping(value="/result")
public class SmthController {

    @RequestMapping(method=RequestMethod.GET)
    public String dosmth(HttpServletRequest request, @RequestParam("name1") String one, @RequestParam("name2") String two, @RequestParam("name3") String three) {

        JOptionPane.showMessageDialog(null,
                " Param 1 is:" +one +" \n Param 2 is: " +two +" \n Param 3 is: " +three);

        return "redirect:/";
    }
}

Additionally, you can use the defaultValue attribute of @RequestParam to establish a default value if param is not set on GET requests.