spring MVC 返回json
2016-06-16 11:35
453 查看
http://hw1287789687.iteye.com/blog/2128304
spring MVC如何返回json呢?
有两种方式:
方式一:使用ModelAndView
Java代码
@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
Java代码
/***
* {"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")
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:
Java代码
@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;
}
spring MVC如何返回json呢?
有两种方式:
方式一:使用ModelAndView
Java代码
@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
Java代码
/***
* {"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")
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:
Java代码
@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;
}
相关文章推荐
- 三十二、Java图形化界面设计——布局管理器之CardLayout(卡片布局)
- java的Cloneable、Serializable接口
- JavaSE 之 ----- Socket 使用
- java设计模式
- Java中生成随机数的方法
- eclipse,android studio 签名打包,获取MD5, SHA1(应用的签名)
- spring--mybatis事务总结
- spring--事务原理
- java 之 23种设计模式
- Java中2+2==5解读
- java中break和continue源码解析
- java开发工具:Myeclipce、Eclipse向下或向上复制快捷键与系统冲突
- 很赞的struts.xml配置
- spring 拦截器过滤登录url 不验证是否登录其他的都拦截验证是否登录才能访问url
- ubuntu 安装jdk1.6
- java.lang.IllegalArgumentException
- Java中产生随机数的两种方法 .
- An error occurred during the org.eclipse.equinox.internal.p2.engine.phases.CheckTrust phase
- eclipse+adt下开发android微信红包自动抢(AccessibilityService类)
- 第一篇:打造专属开发工具Eclipse篇