前后端交互对于json数据的处理和接收
程序员文章站
2022-03-16 08:54:49
...
一、前端传给后端json对象或json字符串
1.以json对象传递(Ajax默认模式)
后端这边没有什么限制都是可以接收到的,比如对象,单个参数等
通过注解@RequestParam进行接收
@ResponseBody
public String test(@RequestParam String username,@RequestParam String password){
}
2.传递JSON字符串给后端(使用application/json格式)
//1.只能封装在实体对象中,不能单独设置参数
@RequestMapping(value="/testJson3",method={RequestMethod.POST})
@ResponseBody
public String testJson3(@RequestBody User user){
System.out.println(user.getUsername());
System.out.println(user.getPassword());
}
//2.封装到Map中
@RequestMapping(value="/testJson4",method={RequestMethod.POST})
@ResponseBody
public String testJson4(@RequestBody Map map){
System.out.println(map.get("username"));
System.out.println(map.get("password"));
}
//3.用String接收
@RequestMapping(value="/testJson5",method={RequestMethod.POST})
@ResponseBody
public String testJson5(@RequestBody String user) throws IOException{
System.out.println(user);
ObjectMapper mapper=new ObjectMapper();
User user1=mapper.readValue(user,User.class);
System.out.println(user1.getUsername());
System.out.println(user1.getPassword());
}
二、后端返回给前端json格式的数据
1.使用jackson类库
<!-- json -->
<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-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
写一个将object转json,并通过response对象将json格式的数据返回给前端的方法
public class BaseController{
protected static JsonFactory factory=mapper.getJsonFactory();
//将对象转成json输出
protected void writeJSON(Object obj) throws IOException{
response.setContentType("text/html;charset=utf-8");
JsonGenerator responseJsonGenerator=factory.createJsonGenerator(response.getOutputStream(),JsonEncoding.UTF8);
responseJsonGenerator.writeObject(obj);
}
}
后端调用
public class Result implements Serializable{
private static final long serialVersionUID=2267751680865696851L;
//是否成功
private Boolean success=false;
//返回消息
private String message;
//返回数据
private Object data;
}
@Controller
@RequestMapping("/sysuser")
public class SysUserController extends BaseController{
@RequestMapping(value="/login")
public void login() throws IOException{
Result result=new Result();
result.setMessage("登录成功");
result.setSuccess(true);
super.writeJSON(result);
}
}
2. 使用springmvc的@RestController注解
//@RestController是@ResponseBody和@Controller的组合注解
//@Controller是用来响应页面的,如果是String类型的方法,则springmvc会跳转到响应的页面
//@ResponseBody是用来响应数据的,如果是对象类型的方法,则springmvc会将结果对象转成json格式输出给前端
//@ResponseBody注解返回响应体,直接将返回值序列化json;不需要自己再处理
@ResponseBody
public Admin loadForm(String username){
Admin admin=adminService.findByUsername(username);
return admin;
}
3. 使用fastjson实现
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
@Controller
@RequestMapping("/login")
public class TestController{
@RequestMapping("/test")
public void test(HttpServletResponse response)throws IOException{
SysUser sysUser=new SysUser();
sysUser.setLoginPass("123456");
sysUser.setLoginAccount("小明");
JSONObject jsonObject=(JSONObject)JSONObject.toJSON(sysUser);//创建json对象
Map<String,String> map=new HashMap<>();
map.put("phone","123456");
map.put("status","ok");
jsonObject.put("info",map);//设置Json对象的属性
System.out.println(jsonObject.toString());//调用toString方法将json对象转换成json字符串
//或者
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(jsonObject.toJSONString());
}
}
后台返回数据给前端,json中文乱码解决方法
-
只需要在spring-mvc.xml配置文件中配置一次就好,省去了我们重复写的麻烦
<!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题--> <mvc:annotation-driven > <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter" > <property name = "supportedMediaTypes"> <list> <value>application/json;charset=utf-8</value> <value>text/html;charset=utf-8</value> <!-- application 可以在任意 form 表单里面 enctype 属性默认找到 --> <value>application/x-www-form-urlencoded</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" ></bean> </mvc:message-converters> </mvc:annotation-driven>
-
在后台的方法映射添加
@RequestMapping(value="/getphone",produces="text/plain;charset=utf-8")
4. 采用工具类,进行json格式转换带回
JSON-lib包是一个beans,collections,maps,java arrays和xml和json互相转换的包
工具类:ResponseUtil.java
public class ResponseUtil{
public static void write(HttpServletResponse response,Object result) throws Exception{
response.setContentType("text/html;charset=utf-8");
response.addHeader("Access-Control-Allow-Origin", "*");
PrintWriter out=response.getWriter();
out.println(result.toString());
System.out.println("带回的json字符串为:"+result.toString()+"类型为:"+result.getClass().getName());
out.flush();
out.close();
}
public static void main(String[] args)throws Exception{
//在web运用控制层中调用
JSONObject result=new JSONObject();//创建json对象
JSONArray jsonArray=JSONArray.fromObject("name:zhangsan");//字符串转为json数组
result.put("rows",jsonArray);//放入json数组中,并起个名字
HttpServletResponse response=null;
ResponseUtil.write(response,result);//将result写入response带回前端
}
}