spring MVC 返回json

236 篇文章 0 订阅
25 篇文章 0 订阅

spring MVC如何返回json呢?

有两种方式:

方式一:使用ModelAndView

@ResponseBody
	@RequestMapping("/save")
	public ModelAndView save(SimpleMessage simpleMessage){
		//查询时可以使用 isNotNull
		if(!ValueWidget.isNullOrEmpty(simpleMessage)){
			try {
				//把对象中空字符串改为null
				ReflectHWUtils.convertEmpty2Null(simpleMessage);
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		simpleMessage.setCreateTime(TimeHWUtil.getCurrentTimestamp());
		simpleMessage.setHasReply(Constant2.SIMPLE_MESSAGE_HAS_REPLY_NOT_YET);
		this.simpleMessageDao.add(simpleMessage);
		Map map=new HashMap();
		map.put("result", "success");
		return new ModelAndView(new MappingJacksonJsonView(),map);
	}

 

 

方式二:返回String

/***
	 * {"fileName":"20141002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\20141002125209_571slide4.jpg"}
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")
	public String upload(
			@RequestParam(value = "image223", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String content = null;
		Map map = new HashMap();
		if (ValueWidget.isNullOrEmpty(file)) {
			map.put("error", "not specify file!!!");
		} else {
			System.out.println("request:" + request);// org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest@7063d827
			System.out.println("request:" + request.getClass().getSuperclass());
			
			// // System.out.println("a:"+element+":$$");
			// break;
			// }
			String fileName = file.getOriginalFilename();// 上传的文件名
			fileName=fileName.replaceAll("[\\s]",	"");//IE中识别不了有空格的json
			// 保存到哪儿
			String finalFileName = TimeHWUtil.formatDateByPattern(TimeHWUtil
					.getCurrentTimestamp(),"yyyyMMddHHmmss")+ "_"
							+ new Random().nextInt(1000) + fileName;
			File savedFile = getUploadedFilePath(request,
					Constant2.UPLOAD_FOLDER_NAME + "/image", finalFileName,
					Constant2.SRC_MAIN_WEBAPP);// "D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\ upload\\pic\\ys4-1.jpg"
			System.out.println("[upload]savedFile:"
					+ savedFile.getAbsolutePath());
			// 保存
			try {
				file.transferTo(savedFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			ObjectMapper mapper = new ObjectMapper();
			
			

			map.put("fileName", finalFileName);
			map.put("path", savedFile.getAbsolutePath());
			try {
				content = mapper.writeValueAsString(map);
				System.out.println(content);
			} catch (JsonGenerationException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
//			System.out.println("map:"+map);
		}

/*
 * {"fileName":"20141002125209_571slide4.jpg","path":"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\upload\\image\\20141002125209_571slide4.jpg"}
 * */
		return content;

	}

 

两种方式有什么区别呢?

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

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

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

使用注解@RequestMapping 中的produces:

@ResponseBody
	@RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")
	public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)
			throws IOException {
		String content = null;
		Map map = new HashMap();
		ObjectMapper mapper = new ObjectMapper();

		map.put("fileName", "a.txt");
		try {
			content = mapper.writeValueAsString(map);
			System.out.println(content);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if("json".equals(contentType2)){
			response.setContentType(SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF);
		}
		return content;

	}

 

@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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值