springMVC接收参数的几种方式

目录

前言

在使用springmvc的过程中,经常会遇到前端发送不同类型的数据,而后台也有不同的接收方式;

正文

springmvc可以使用一下几种方式来获取数据:

  1. 直接根据属性名和类型接收参数
  2. 通过bean来接收数据
  3. 通过HttpServletRequest来获取数据
  4. 通过@PathVariable获取路径参数
  5. 通过@RequestParam来获取参数

直接根据属性名和类型接收参数

  1. URL形式:

​ http://localhost:8080/test/one 表单提交数据,其中属性名与接收参数的名字一致;

​ http://localhost:8080/test/one?name=aaa 数据显示传送

注意:delete请求用表单提交的数据后台无法获取,得将参数显示传送;

  1. controller端的代码
    @RequestMapping("/one")
    public String testOne(String name){
        System.out.println(name);
        return "success";
    }

说明:直接将属性名和类型定义在方法的参数中,前提是参数名字必须得跟请求发送的数据的属性的名字一致,而且这种方式让请求的参数可为空,请求中没有参数就为null;

通过bean来接收数据

  1. URL形式:

http://localhost:8080/test/two 表单提交数据,其中属性名与接收的bean内的属性名一致;

http://localhost:8080/test/two?username=aa&password=bb 数据显示传送

  1. 构建一个Userbean
public class Test { 
    private String username;
    private String password;
}

get,set,tostring没贴上来

  1. 后端请求处理代码
    @RequestMapping("/two")
    public String testTwo(User user){
        System.out.println(user.toString());
        return "success";
    }

说明:User类中一定要有set,get方法,springmvc会自动将与User类中属性名一致的数据注入User中,没有的就不注入;

通过HttpServletRequest来获取数据

  1. URL形式:

​ http://localhost:8080/test/three 采用表单提交数据

​ http://localhost:8080/test/three?username=aa 数据显示传送

  1. 后端请求处理代码:
    @RequestMapping("/three")
    public String testThree(HttpServletRequest request){
        String username = request.getParameter("username");
        System.out.println(username);
        return "success";
    }

说明:后端采用servlet的方式来获取数据,但是都用上框架了,应该很少用这种方式来获取数据了吧;

通过@PathVariable获取路径参数

  1. URL形式

http://localhost:8080/test/four/aaa/bbb

  1. 后端请求处理代码:
@RequestMapping("/four/{username}/{password}")
    public String testFour(
                           @PathVariable("username")String username,
                           @PathVariable("password")String password
    ){
        System.out.println(username);
        System.out.println(password);
        return "success";
    }

说明:@PathVariable注解会将请求路径中对应的数据注入到参数中

注意:@PathVariable注解的数据默认不能为空,就是请求路径中必须带有参数,不能为空,如果请求数据为空,则需要在@PathVariable中将required属性改为false;

通过@RequestParam来获取参数

  1. URL形式

http://localhost:8080/test/five 表单提交数据,未显示传送

http://localhost:8080/test/two?username=aa&password=bb 数据显示传送

  1. 后端处理代码
 @RequestMapping("/five")
    public String testFive(@RequestParam(value = "username")String username,
                           @RequestParam("password")String password
    ){
        System.out.println(username);
        System.out.println(password);
        return "success";
    }

说明: @RequestParam会将请求中相对应的数据注入到参数中,

注意: @RequestParam注解的参数也是不能为空的,如果需要为空,则需要将required属性改为false,还有就是 @RequestParam注解中的defaultValue 属性可以为参数设置默认值;

最后

感谢哥们能看到这里!哈哈!

猜你喜欢

转载自www.cnblogs.com/guoyuchuan/p/9467418.html
今日推荐