href具有多个参数弹簧

时间:2012-05-10 07:09:27

标签: spring url parameters

我想通过以下方式向控制器发送3个参数:

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

控制器:

@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:/";
    }
}

2 个答案:

答案 0 :(得分:2)

您的代码没问题,但这是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:/";
    }
}

此外,如果未在GET请求中设置param,则可以使用@RequestParam的defaultValue属性来建立默认值。

答案 1 :(得分:0)

我更喜欢使用Map简化方法签名:

@RequestMapping(method=RequestMethod.GET)
public String dosmth(@RequestParam Map<String, String> map) {
    System.out.println("Param 1 is:" + map.get("paramName1") + "Param 2 is:" + map.get("paramName2"));
    return "redirect:/";
}