spring MVC 返回json

简介:

spring MVC如何返回json呢?

有两种方式:

方式一:使用ModelAndView

Java代码   收藏代码
  1. @ResponseBody  
  2.     @RequestMapping("/save")  
  3.     public ModelAndView save(SimpleMessage simpleMessage){  
  4.         //查询时可以使用 isNotNull  
  5.         if(!ValueWidget.isNullOrEmpty(simpleMessage)){  
  6.             try {  
  7.                 //把对象中空字符串改为null  
  8.                 ReflectHWUtils.convertEmpty2Null(simpleMessage);  
  9.             } catch (SecurityException e) {  
  10.                 e.printStackTrace();  
  11.             } catch (NoSuchFieldException e) {  
  12.                 e.printStackTrace();  
  13.             } catch (IllegalArgumentException e) {  
  14.                 e.printStackTrace();  
  15.             } catch (IllegalAccessException e) {  
  16.                 e.printStackTrace();  
  17.             }  
  18.         }  
  19.         simpleMessage.setCreateTime(TimeHWUtil.getCurrentTimestamp());  
  20.         simpleMessage.setHasReply(Constant2.SIMPLE_MESSAGE_HAS_REPLY_NOT_YET);  
  21.         this.simpleMessageDao.add(simpleMessage);  
  22.         Map map=new HashMap();  
  23.         map.put("result""success");  
  24.         return new ModelAndView(new MappingJacksonJsonView(),map);  
  25.     }  

 

 

方式二:返回String

Java代码   收藏代码
  1. /*** 
  2.      * {"fileName":"20141002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\20141002125209_571slide4.jpg"} 
  3.      * @param file 
  4.      * @param request 
  5.      * @param response 
  6.      * @return 
  7.      * @throws IOException 
  8.      */  
  9.     @ResponseBody  
  10.     @RequestMapping(value = "/upload")  
  11.     public String upload(  
  12.             @RequestParam(value = "image223", required = false) MultipartFile file,  
  13.             HttpServletRequest request, HttpServletResponse response)  
  14.             throws IOException {  
  15.         String content = null;  
  16.         Map map = new HashMap();  
  17.         if (ValueWidget.isNullOrEmpty(file)) {  
  18.             map.put("error""not specify file!!!");  
  19.         } else {  
  20.             System.out.println("request:" + request);// org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest@7063d827  
  21.             System.out.println("request:" + request.getClass().getSuperclass());  
  22.               
  23.             // // System.out.println("a:"+element+":$$");  
  24.             // break;  
  25.             // }  
  26.             String fileName = file.getOriginalFilename();// 上传的文件名  
  27.             fileName=fileName.replaceAll("[\\s]",   "");//IE中识别不了有空格的json  
  28.             // 保存到哪儿  
  29.             String finalFileName = TimeHWUtil.formatDateByPattern(TimeHWUtil  
  30.                     .getCurrentTimestamp(),"yyyyMMddHHmmss")+ "_"  
  31.                             + new Random().nextInt(1000) + fileName;  
  32.             File savedFile = getUploadedFilePath(request,  
  33.                     Constant2.UPLOAD_FOLDER_NAME + "/image", finalFileName,  
  34.                     Constant2.SRC_MAIN_WEBAPP);// "D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\ upload\\pic\\ys4-1.jpg"  
  35.             System.out.println("[upload]savedFile:"  
  36.                     + savedFile.getAbsolutePath());  
  37.             // 保存  
  38.             try {  
  39.                 file.transferTo(savedFile);  
  40.             } catch (Exception e) {  
  41.                 e.printStackTrace();  
  42.             }  
  43.               
  44.             ObjectMapper mapper = new ObjectMapper();  
  45.               
  46.               
  47.   
  48.             map.put("fileName", finalFileName);  
  49.             map.put("path", savedFile.getAbsolutePath());  
  50.             try {  
  51.                 content = mapper.writeValueAsString(map);  
  52.                 System.out.println(content);  
  53.             } catch (JsonGenerationException e) {  
  54.                 e.printStackTrace();  
  55.             } catch (JsonMappingException e) {  
  56.                 e.printStackTrace();  
  57.             } catch (IOException e) {  
  58.                 e.printStackTrace();  
  59.             }  
  60. //          System.out.println("map:"+map);  
  61.         }  
  62.   
  63. /* 
  64.  * {"fileName":"20141002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\20141002125209_571slide4.jpg"} 
  65.  * */  
  66.         return content;  
  67.   
  68.     }  

 

两种方式有什么区别呢?

方式一:使用ModelAndView的contentType是"application/json"

方式二:返回String的            contentType是"text/html"

那么如何设置response的content type呢?

使用注解@RequestMapping 中的produces:

Java代码   收藏代码
  1. @ResponseBody  
  2.     @RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")  
  3.     public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)  
  4.             throws IOException {  
  5.         String content = null;  
  6.         Map map = new HashMap();  
  7.         ObjectMapper mapper = new ObjectMapper();  
  8.   
  9.         map.put("fileName""a.txt");  
  10.         try {  
  11.             content = mapper.writeValueAsString(map);  
  12.             System.out.println(content);  
  13.         } catch (JsonGenerationException e) {  
  14.             e.printStackTrace();  
  15.         } catch (JsonMappingException e) {  
  16.             e.printStackTrace();  
  17.         } catch (IOException e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.         if("json".equals(contentType2)){  
  21.             response.setContentType(SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF);  
  22.         }  
  23.         return content;  
  24.   
  25.     }  

 

@RequestMapping(value ="/upload",produces="application/json;charset=UTF-8")

@RequestMapping(value = "/upload",produces="application/json")

spring 官方文档说明:

Producible Media Types

You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the producescondition. For example:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
    // implementation omitted
}

Just like with consumes, producible media type expressions can be negated as in !text/plain to match to all requests other than those with an Accept header value oftext/plain.

Tip
[Tip]

The produces condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level producible types override rather than extend type-level producible types.

 

参考:http://hw1287789687.iteye.com/blog/2128296

http://hw1287789687.iteye.com/blog/2124313

相关文章
|
7月前
|
前端开发 Java 测试技术
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
362 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
|
7月前
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
546 0
|
7月前
|
前端开发 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping("/user/{id}")` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable("自定义名")` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
360 0
|
7月前
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = "/test", produces = "application/json; charset=UTF-8")`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
318 0
|
7月前
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
232 0
|
7月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult<T>`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码"0"和消息"操作成功!",有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
557 0
|
3月前
|
JSON Java 数据格式
Spring Boot返回Json数据及数据封装
在Spring Boot中,接口间及前后端的数据传输通常使用JSON格式。通过@RestController注解,可轻松实现Controller返回JSON数据。该注解是Spring Boot新增的组合注解,结合了@Controller和@ResponseBody的功能,默认将返回值转换为JSON格式。Spring Boot底层默认采用Jackson作为JSON解析框架,并通过spring-boot-starter-json依赖集成了相关库,包括jackson-databind、jackson-datatype-jdk8等常用模块,简化了开发者对依赖的手动管理。
406 3
|
3月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
213 0
|
3月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
121 0
|
3月前
|
JSON 前端开发 Java
第05课:Spring Boot中的MVC支持
第05课:Spring Boot中的MVC支持
187 0

热门文章

最新文章