美文网首页
springMVC(六)json请求和json响应

springMVC(六)json请求和json响应

作者: 探索的影子 | 来源:发表于2018-08-22 18:11 被阅读0次

首先我们先实现一次key\value请求,然后在实现json请求,响应都使用json格式。

需求:根据学院id查询学院信息。

前端页面实现:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.2.1.min.js"></script>
</head>

<body>
<input type="button" id="uid" />
<script>
    $("#uid").click(function(){
        //取Ajax返回结果
        //为了简单,这里简单地从文件中读取内容作为返回数据
        $.ajax({
            type: "post",
            url: "${pageContext.request.contextPath}/faculty/selectFacultyById3.action",
            dataType : "json",
            success: function (data)
            {
                var result =  eval(data);
                alert(result.facultyId);
                $("#hh").append("<p>学院编号:"+result.facultyId+" 学院名称:"+result.facultyName+"</p>");
            },
            error:function (XMLHttpRequest,textStatus,errorThrown) {
                alert("请求失败!");
            }
        });
    });
</script>
    <h1 id="hh">将内容添加到h1,里面作为子元素:<p id="list"></p></h1>

</body>
</html>

controller层

这里发过来的是普通请求,当然因为方便,我直接设置了defaultValue。json响应只需要用注解@ResponseBody修饰即可。(啊喂,你别告诉我处理json的包还没导入进来这是我从其他地方复制的)

<!-- 映入JSON -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.1</version>
      <classifier>jdk15</classifier>
    </dependency>

controller具体实现:

    @RequestMapping("/selectFacultyById3.action")
    public @ResponseBody Faculty selectFacultyById3(@RequestParam(value = "facultyCustom.facultyId",defaultValue = "1") Integer facultyId){
        Faculty faculty = facultyService.selectFacultyByFacultyId(facultyId);
        return faculty;
    }

测试:

image.png

查看响应的json数据:


image.png

解析出来的结果:


image.png

添加到页面的指定位置:


image.png

注意controller层返回结果就是你需要返回的json字符串,别用ModelAndView这种奇怪的东西~~~

请求方式json方式

这里遇到一个好大好大的坑:controller层接受json
一定要用对象!
不然参数绑定不上!!!!!!!
当然更不要用@RequestParam修饰Integer,String等包装类和对象。(如果请求类型不是json那就无所谓)

错误集锦:
使用包装类Integer
错误代码如下:

    @RequestMapping("/select.action")
    public @ResponseBody Faculty select(@RequestBody Integer facultyId){
        Faculty faculty = facultyService.selectFacultyByFacultyId(facultyId);
        return faculty;
    }

错误现象:


image.png

这种错误很难察觉,一般都会认为路径存在问题,无论怎么改都是404-错误。。然后就会想清除缓存然后发现还是没用。就会写个普通的方法,却发现有用。一旦使用了@RequestBody就抽风。。。这就是我的测试步骤。。。。。(其实就是初学,对于接受参数不懂)


后记
之前发生错误的原因400,可以理解为参数绑定之类的错误,就是springmvc没有绑定成功导致错误。
解决方案一:
@RequestBody Map<String,String> map;
使用map接受参数
解决方案二:
使用对象,属性对应名字。


controller层


    @RequestMapping("/select.action")
    public @ResponseBody Faculty select(@RequestBody Faculty facultyTemp){
        Faculty faculty = facultyService.selectFacultyByFacultyId(facultyTemp.getFacultyId());
        return faculty;
    }

jsp页面
改动部分是contentType: "application/json",设置请求类型data : JSON.stringify(json)这是讲数组转为json对象。之前获取到的json用的是eval解析。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.2.1.min.js"></script>
</head>

<body>
<input type="button" id="uid" />
<script>
    $("#uid").click(function(){
        var json = {
            "facultyId": 2
        };
        $.ajax({
            type: "post",//post请求方式
            url: "${pageContext.request.contextPath}/faculty/select.action",
            contentType: "application/json",
            data : JSON.stringify(json),
            dataType : "json",//响应格式为json
            success: function (data)
            {
                var result =  eval(data);//处理json
                alert(result.facultyId);//测试处理结果
                $("#hh").append("<p>学院编号:"+result.facultyId+" 学院名称:"+result.facultyName+"</p>");//添加到指定位置
            },
            error:function (XMLHttpRequest,textStatus,errorThrown) {
                alert("请求失败!");
            }
        });
    });
</script>
    <h1 id="hh">将内容添加到h1,里面作为子元素:<p id="list"></p></h1>

</body>
</html>

测试结果:


image.png

请求内容:

image.png

响应内容:


image.png

springmvc就算是结束了。。。validate校验比较简单看后面会不会补充。


明天更新的内容是json,主要是因为json这个东西无论是前端人员,还是后端人员都需要处理json。那么明天我将会用jquery ajax对json进行一些操作。

相关文章

网友评论

      本文标题:springMVC(六)json请求和json响应

      本文链接:https://www.haomeiwen.com/subject/zyryiftx.html