Spring MVC 处理JSON | JSONP类型数据

SpringMVC返回JSON格式的数据:

  1 添加jar包(gson-2.8.0.jar):

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

    或者(jackson-databind-2.1.5.jar):

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

   2 在controller中配置注解:   

      方法的返回值就是需要的对象

      @ResponseBody会自动调用包中的方法将数据转为json格式

    @ResponseBody
    @RequestMapping(value="/users-json", method=RequestMethod.GET)
    public Collection<User> listjson() {
        //显示列表
        return userDao.getAll();
    }

 SpringMVC返回JSONP格式的数据:

  1 使用gson

    js只有数组,数组具有所有集合的特性

    jquery实现jsonp环境:动态生成了一个script标签,将请求转发到远程地址

    script标签必须定义到callback方法后面

@RequestMapping(value="/users-jsonp", method=RequestMethod.GET)
    public void listjson(String callback, HttpServletResponse response) throws IOException {
        //显示列表
        Collection<User> list = userDao.getAll();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        response.getWriter().println(callback + "(" + json + ")");
    }
<script>
  function showdata(data){
      console.log(data);
  }
</script>
<script src="http://localhost:8080/springmvc-02-mvn/users-jsonp?callback=showdata">
</script>

  2 使用spring内置的处理方式:

@RequestMapping(value="/user/checklogin2/{token}", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String checkLogin(@PathVariable String token, String callback){
    MessageResult result = ssoService.getUserByToken(token);
    String json = JsonUtils.objectToJson(result);
    String returnStr = callback + "(" + json + ")";
    return returnStr;
}

  3 使用springMVC提供的类:

@RequestMapping(value="/user/checklogin2/{token}", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String checkLogin(@PathVariable String token, String callback){
    MessageResult result = ssoService.getUserByToken(token);
    String json = JsonUtils.objectToJson(result);
    String returnStr = callback + "(" + json + ")";
    return returnStr;
}

  SpringMVC提交JSON格式的数据:

   对表单进行json提交(使用ajax):

 $(function(){
        $('#saveBtn').click(function(){
        //创建javascript对象 var row
= { username: $('#username').val(), password: $('#password').val(), age: $('#age').val(), } $.ajax({ url: 'user-json', type: 'post' , contentType: 'application/json;charset=utf-8',//声明请求头的内容类型 data: JSON.stringify(row)//将js对象转为json串 }); }); });
    @RequestMapping(value="/user-json", method=RequestMethod.POST)
    public String savejson(@RequestBody User user) {

        userDao.save(user);
        return "redirect:/users";
    }
原文地址:https://www.cnblogs.com/roxy/p/7604026.html