spring MVC 返回json


1、第一种方式是spring2时代的产物,也就是每个json视图controller配置一个Jsoniew。

如:<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/> 

或者<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>

同样要用jackson的jar包。


2、第二种使用JSON工具将对象序列化成json,常用工具Jackson,fastjson,gson。

利用HttpServletResponse,然后获取response.getOutputStream()或response.getWriter()

直接输出。

示例:

  1. public class JsonUtil  
  2. {  
  3.       
  4.     private static Gson gson=new Gson();  
  5.   
  6.   
  7.     /** 
  8.      * @MethodName : toJson 
  9.      * @Description : 将对象转为JSON串,此方法能够满足大部分需求 
  10.      * @param src 
  11.      *            :将要被转化的对象 
  12.      * @return :转化后的JSON串 
  13.      */  
  14.     public static String toJson(Object src) {  
  15.         if (src == null) {  
  16.             return gson.toJson(JsonNull.INSTANCE);  
  17.         }  
  18.         return gson.toJson(src);  
  19.     }  
  20. }  
public class JsonUtil
{
    
    private static Gson gson=new Gson();


    /**
     * @MethodName : toJson
     * @Description : 将对象转为JSON串,此方法能够满足大部分需求
     * @param src
     *            :将要被转化的对象
     * @return :转化后的JSON串
     */
    public static String toJson(Object src) {
        if (src == null) {
            return gson.toJson(JsonNull.INSTANCE);
        }
        return gson.toJson(src);
    }
}


3、第三种利用spring mvc3的注解@ResponseBody

例如:

  1. @ResponseBody  
  2.   @RequestMapping("/list")  
  3.   public List<String> list(ModelMap modelMap) {  
  4.     String hql = "select c from Clothing c ";  
  5.     Page<Clothing> page = new Page<Clothing>();  
  6.     page.setPageSize(6);  
  7.     page  = clothingServiceImpl.queryForPageByHql(page, hql);  
  8.       
  9.     return page.getResult();  
  10.   }  
@ResponseBody
  @RequestMapping("/list")
  public List<String> list(ModelMap modelMap) {
    String hql = "select c from Clothing c ";
    Page<Clothing> page = new Page<Clothing>();
    page.setPageSize(6);
    page  = clothingServiceImpl.queryForPageByHql(page, hql);
    
    return page.getResult();
  }

然后使用spring mvc的默认配置就可以返回json了,不过需要jackson的jar包哦。

注意:当springMVC-servlet.xml中使用<mvc:annotation-driven />时,如果是3.1之前已经默认注入AnnotationMethodHandlerAdapter,3.1之后默认注入RequestMappingHandlerAdapter只需加上上面提及的jar包即可!

如果是手动注入RequestMappingHandlerAdapter 可以这样设置

配置如下:

<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><strong>[html]</strong> <a target=_blank title="view plain" class="ViewSource" href="http://blog.csdn.net/shan9liang/article/details/42181345#">view plain</a><a target=_blank title="copy" class="CopyToClipboard" href="http://blog.csdn.net/shan9liang/article/details/42181345#">copy</a><a target=_blank title="print" class="PrintSource" href="http://blog.csdn.net/shan9liang/article/details/42181345#">print</a><a target=_blank title="?" class="About" href="http://blog.csdn.net/shan9liang/article/details/42181345#">?</a></div></div><ol class="dp-xml"><li class="alt"><span><span class="tag"><</span><span class="tag-name">bean</span><span> </span><span class="attribute">class</span><span>=</span><span class="attribute-value">"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"</span><span>  </span></span></li><li><span>        <span class="attribute">p:ignoreDefaultModelOnRedirect</span><span>=</span><span class="attribute-value">"true"</span><span> </span><span class="tag">></span><span>  </span></span></li><li class="alt"><span>            <span class="tag"><</span><span class="tag-name">property</span><span> </span><span class="attribute">name</span><span>=</span><span class="attribute-value">"messageConverters"</span><span class="tag">></span><span>  </span></span></li><li><span>                <span class="tag"><</span><span class="tag-name">list</span><span class="tag">></span><span>  </span></span></li><li class="alt"><span>                    <span class="tag"><</span><span class="tag-name">bean</span><span> </span><span class="attribute">class</span><span>=</span><span class="attribute-value">"org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"</span><span class="tag">/></span><span>  </span></span></li><li><span>                <span class="tag"></</span><span class="tag-name">list</span><span class="tag">></span><span>  </span></span></li><li class="alt"><span>            <span class="tag"></</span><span class="tag-name">property</span><span class="tag">></span><span>  </span></span></li><li><span>        <span class="tag"></</span><span class="tag-name">bean</span><span class="tag">></span><span>  </span></span></li></ol></div><pre class="html" style="display: none;" name="code"><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
		p:ignoreDefaultModelOnRedirect="true" >
			<property name="messageConverters">
				<list>
					<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
				</list>
			</property>
		</bean>
 


添加包
jackson-mapper-asl-*.jar
jackson-core-asl-*.jar




有两种方式:

方式一:使用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.     }  
@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代码 复制代码  收藏代码
  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.     }  
/***
	 * {"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代码 复制代码  收藏代码
  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.     }  
@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
[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、付费专栏及课程。

余额充值