2

我想通过以下方式向控制器发送 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:/";
    }
}
4

2 回答 2

2

您的代码没问题,但这是 Spring 方式:

@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 请求上设置参数,您可以使用 @RequestParam 的 defaultValue 属性来建立默认值。

于 2012-05-10T08:35:07.667 回答
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:/";
}
于 2013-04-13T18:10:15.517 回答