欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC(四):接收参数的方式

程序员文章站 2022-07-12 20:47:27
...

一.SpringMVC参数接收思维导图

 

SpringMVC(四):接收参数的方式

二.接收参数实例

1.普通方式接受参数

1.1.控制端代码

@Controller
@RequestMapping("requestParam")
public class RequestParamsController {

    @RequestMapping("requestParam")
    public ModelAndView requestParams( String user_id){
        System.out.println("user_id:"+userId);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/springMVC/paramRequest/RequestParams");
        return mv;
    }
}

1.2.前端jsp代码

<form action="<%=path%>/param/commonParam">
    <input type="text" name="user_id">
    <input type="text" name="user_password">
    <input type="submit" value="提交">
</form>

1.3.提交之后便会看到结果输出,两端参数名字相同才能接收,view端name为h5中input的name属性。

2.RequestParam接收参数

2.1.控制端代码

@Controller
@RequestMapping("requestParam")
public class RequestParamsController {

    @RequestMapping("requestParam")
    public ModelAndView requestParams(@RequestParam(value = "user_id",required = false) String userId){
        System.out.println("user_id:"+userId);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/springMVC/paramRequest/RequestParams");
        return mv;
    }
}

2.2.前端jsp代码

<form action="<%=path%>/requestParam/requestParam">
    <input type="text" name="user_id">
    <input type="text" name="user_password">
    <input type="submit" value="提交">
</form>

2.3.view端name为h5中input的name属性,@RequestParam默认参数不为空,否则会出现400异常,需要为空,则设置:@RequestParam(value = "user_id",required = false)

3.使用URL传递参数

3.1.控制端代码

@Controller
@RequestMapping("urlParam")
public class UrlParamsController {

    @RequestMapping("/urlParam/{id}")
    public ModelAndView urlParams(@PathVariable("id") int id){
        User user = new User();
        user.setUserId(String.valueOf(id));
        ModelAndView mv = new ModelAndView();
        mv.addObject(user);
        mv.setView(new MappingJackson2JsonView());
        return mv;

    }
}

3.2.前端没有代码,直接使用new MappingJackson2JsonView()显示数据,注意其只能返回显示对象类型数据,该方法在org.springframework.web.servlet.view.json.MappingJackson2JsonView包下;@PathVariable表示从URL请求地址中获取的参数,允许为空。

4.传递JSON数据

4.1.前端代码,引入JQ.

<script>
        $(document).ready(function () {
            $("#start").click(function () {
                alert("点击了");
                var user={
                        userId: "e",
                        userNickName: "hly",
                        userPassword: "qq",

                    }
                $.ajax({
                    url:"<%=path%>/jsonParam/jsonParam/",
                    type : "POST",
                    data:JSON.stringify(user),
                    contentType:'application/json',
                    dataType : 'json',
                    beforeSend : function () {
                        console.log(user);
                    },
                    success:function () {
                        alert("传递成功");
                    },
                    error:function () {
                        alert("错误了");
                    }
                });
            });
        });
    </script>

1.contentType:发送什么类型的数据到服务器,dataType:服务器返回的是什么类型的数据。

2.可能会出现的错误:

2.1.400错误:前端传递过来的属性和后端不一致.

2.2.414错误:

2.2.1.前端JSON属性必须和传递的pojo的属性对应,顺序无所谓,属性名字一直就行.

2.2.2.前端ajax里的关键字区分大小写(重点),否则也会出现404错误.

2.2.3.需要添加相关的JSONjar.

4.2.后端代码

@RequestMapping("jsonParam")
    public ModelAndView jsonParam(@RequestBody User user) {

        System.out.println(user.toString());
        ModelAndView mv = new ModelAndView();
        //mv.addObject(json);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

4.3.pojo的属性

public class User {
    private String userId;
    private String userNickName;
    private String userPassword;
    }

4.4.springMVC的配置

    <!--使用注解驱动,没有就不能扫描@Controller,就会出现404-->
    <!-- 一个配置节解决映射器和适配器的配置注解配置 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--是用于**那些已经在spring容器里注册过的bean-->
    <context:annotation-config />

    <!--定义扫描装载的包-->
    <!--具有<context:annotation-config>的功能-->
    <context:component-scan base-package="com.*"></context:component-scan>

4.5.JSON的maven依赖,spring版本是4.0

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.3</version>
        </dependency>

        <!-- 各种json 配置开始 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20150729</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

5.接收列表和表单数据

5.1.前端代码

<form id="form">
    <input type="text" name="userId">
    <input type="text" name="userPassword">
    <input type="submit" name="submit" id="submit">
    </form>

将表单数据转化为字符串传递给后端

$("#submit").click(function () {
                var str = $("form").serialize();
                $.ajax({
                    url: "<%=path%>/listParam/formParam/",
                    type: "POST",
                    data: str,
                });
            });

5.2.后端代码

@RequestMapping("formParam")
    public ModelAndView formParams(String userId,String userPassword){
        System.out.println(userId+" "+userPassword);
        ModelAndView mv = new ModelAndView();
        return mv;

    }

前后端传递的标识符保持一致

完整代码请在笔者github中查看