java技术--Controller接收参数的几种常用方式

1.在SpringMVC后台控制层获取参数的方式主要有两种

(1)一种是request.getParameter("name")
(2)另外一种是用注解@RequestParam直接获取
       <1>@RequestParam(value="collectorId") String collectorId
       <2>value可以省略:@RequestParam("collectorId") String collectorId

2.@PathVariable、@RequestParam 、@RequestBody的区别

(1)@PathVariable也可以获取参数
     <1>在url中已经预留了变量的占位符时,需要使用@PathVariable
     <2>是路径(path)上的变量(variable),例如:
         @RequestMapping(value="/springmvc/{param1}", method = RequestMethod.GET)
         public String getDetails (
         @PathVariable("param1") String param1) {...}
      <3>实现GET请求的url是:http://localhost:8080/springmvc/param1value
      <4>由于使用@PathVariable需要将参数带在URL后面,不安全,因此一般不用这种方式
(2)@RequestParam获取参数 
      <1>url中没有预留参数的占位符时,需要使用@RequestParam
      <2>是请求(Request)中的参数(Param),提交方式GET、POST
         @RequestMapping(value="/springmvc", method = RequestMethod.GET)
         public String getDetails (
         @RequestParam("param1", required=true) String param1,
         @RequestParam(value="param2", required=false) String param2){...}  
      <3>>实现GET请求的url是:http://localhost:8080/springmvc?param1=10&param2=20  
      <4>value可以省略,并且默认required=true也可以省略
(3)@RequestBody获取参数
      <1>在url中没有预留参数的占位符,且请求中包含结构体对象时,需要使用@RequestBody
      <2>是请求(Request)中的结构体对象(Body)
      <3>应用实例:User为对象
          @RequestMapping(value="/springmvc", method = RequestMethod.GET)
          public String getDetails (@RequestBody User user) {... }     
      <4>实现GET请求的url是:
           $scope.user = {
                          username: "foo",
                          auth: true,
                          password: "bar"};    
           $http.get('http://localhost:8080/springmvc', $scope.user)    
发布了143 篇原创文章 · 获赞 10 · 访问量 7558

猜你喜欢

转载自blog.csdn.net/qq591009234/article/details/103564955
今日推荐