Spring MVC常见的三种URL请求参数的处理

时间:2021-11-18 20:38:50
    //方法1:@RequestParam
    //url:/test1?id=123
    @RequestMapping(value = "/test1",method = RequestMethod.GET)
    public String test1(@RequestParam String id, Model model){
        model.addAttribute("id","test1:"+id);
        return "/teacher/test";
    }

    //方法2:@PathVariable
    //url:/test2/123
    @RequestMapping(value = "/test2/{id}",method = RequestMethod.GET)
    public String test2(@PathVariable String id, Map<String,Object> model){
        model.put("id","test2:"+id);
        return "/teacher/test";
    }

    //方法3:传统的HttpServletRequest
    //url:/test3/?id=123
    @RequestMapping(value = "/test3",method = RequestMethod.GET)
    public String test3(HttpServletRequest request){
        request.setAttribute("id","test3:"+request.getParameter("id"));
        return "/teacher/test";
    }

注:方法1中的model其实就是一map类型,所以在方法2中可以map类型的入参