Spring MVC中JSON数据处理方式!!!

添加json依赖

 
    
        com.fasterxml.jackson.core
        jackson-databind
        2.9.0
    

注解

  • @RequestBody:作用是接收前端ajax传递给后端的json字符串,并将json格式的数据转为java对象

  • @ResponseBody:作用是将java对象转为json格式的数据传递给前台ajax

案例

  • 编写controller

@Controller
@RequestMapping("/account")
public class AccountController {

    @PostMapping("/findAccount12")
    @ResponseBody
    public JsonStatus findAccount12(@RequestBody Account account) {
        //Map map = new HashMap<>();
        //map.put("status",200);
        //map.put("msg",account);
        JsonStatus jsonStatus = new JsonStatus();
        try {
            //System.out.println(1/0);
            jsonStatus.setStatus(200);
            jsonStatus.setMsg(account);
        } catch (Exception e) {
            e.printStackTrace();
            jsonStatus.setStatus(500);
            jsonStatus.setMsg("查询错误!!!");
        }
        return jsonStatus;
    }
}

添加实体类:

/*
 * Copyright (c) 2020, 2024,  All rights reserved.
 *
 */
package com.by.pojo;

/**
 * 

Project: SpringMVC - JsonStatus

*

Powered by scl On 2024-01-09 17:03:33

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ public class JsonStatus { private Integer status; private Object msg; public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Object getMsg() { return msg; } public void setMsg(Object msg) { this.msg = msg; } }

在index.jsp里面定义ajax请求

  • 添加按钮

引入js库文件

编写ajax代码

  

结果展示:

Spring MVC中JSON数据处理方式!!!_第1张图片

你可能感兴趣的:(spring,mvc,json)