专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 几种SpringMVC接收参数的方式

几种SpringMVC接收参数的方式

更新时间:2022-07-25 09:44:49 来源:动力节点 浏览1079次

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

URL形式:

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

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

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

controller端的代码

    @RequestMapping("/one")
    public String testOne(String name){
        System.out.println(name);
        return "success";
    }

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

通过bean来接收数据

URL形式:

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

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

构建一个Userbean

public class Test { 
    private String username;
    private String password;
}

get,set,tostring没贴上来

后端请求处理代码

    @RequestMapping("/two")
    public String testTwo(User user){
        System.out.println(user.toString());
        return "success";
    }

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

通过HttpServletRequest来获取数据

URL形式:

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

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

后端请求处理代码:

    @RequestMapping("/three")
    public String testThree(HttpServletRequest request){
        String username = request.getParameter("username");
        System.out.println(username);
        return "success";
    }

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

通过@PathVariable获取路径参数

URL形式

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

后端请求处理代码:

@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来获取参数

URL形式

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

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

后端处理代码

 @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 属性可以为参数设置默认值。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>