zoukankan      html  css  js  c++  java
  • Spring MVC JSON交互

    Spring MVC JSON交互

    1.配置

    在Spring MVC的处理流程中的HandlerAdapter部分增加了对JSON格式的转换。需要在HandlerAdapter中配置对应的messageConverters。将配置添加到Spring MVC的配置文件中,代码:

    <!--注解适配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    	<property name="messageConverters">
    	<list>
    	<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    	</bean>
    	</list>
    	</property>
    </bean>
    

    使用<mvc:annotation-driven />则不需要配置。(此标签默认加载了一系列的默认配置,不只是HandlerMapper、和HandlerAdapter.我们这么懒当然使用这个喽)

    Spring MVC提供的这个messageConverters内部使用的是jackson的类库。所以这里需要加入jar包:jackson-core-asl-1.9.11.jar、jackson-mapper-asl-1.9.11.jar

    2.格式

    Spring MVC中处理JSON使用的是两个注解。@RequestBody@ResponseBody。他们均加在对象前面,将JAVA对象与JSON对象自动转换。

    @RequestBody - 将请求转换成JAVA对象。
    @ResponseBody - 将JAVA对象转换成JSON对象。

    所以,在请求数据为JSON数据的时候使用@RequestBody,在响应数据为JSON的时候使用@ResponseBody

    典型用法:

    JSON请求,JSON响应(已删去不必要的部分)

    //前台代码
    function loadMore() {
    	$.ajax({
    		type:"post",
    		url:"/blog/loadMore.action",
    		contentType:"application/json;charset=utf-8;", 
    		data:'{"pageIndex":10}',
    		error: function(request) {},
    		success : function(data){
    			if(null!=data && data.length>0){
    			}else{}
    		}
    	});
    }
    
    //后台代码
    @RequestMapping("/loadMore")
    public @ResponseBody List<Blog> loadMore(@RequestBody BlogJsonVO json,HttpSession session) throws Exception {
    	List<Blog> blogList = blogService.getBlogList(1, json.getPageIndex());
    	return blogList;
    }
    

    FORM请求,JSON响应

    //前台代码
    function save(){
    	 $.ajax({
    	 	type: "POST",
    	 	url:contextPath + '/blog/save.action',
    		data:'content=some&uid=1',
    	    error: function(request) {
    	        alert(" 发生未知错误 ");
    	    },
    	    success: function(data) {
    	    	if(data){
    			}
    	    }
    	}); 
    }
    //后台代码
    @RequestMapping("/save")
    public @ResponseBody Blog save(Blog blog,HttpServletRequest req) throws Exception {
    	String content = blog.getContent();
    	if(StringUtils.isNoneBlank(content)){
    		blogService.addBlog(blog);
    		return blog;
    	}
    	return null;
    }
    

    3.注意:

    • contentType:"application/json;charset=utf-8;",表明了提交的数据是JSON格式的,此时后台的接收对象前需要加@RequestBody。JQuery的AJAX请求默认使用的是application/x-www-form-urlencoded;charset=utf-8此时使用@RequestBody会报415。

    • 在上面的基础上,data的格式需要做对应调整。参照上面代码

    • 浏览器报415,因为jar包没有加或者后台没有加接收的注解@RequestBody

    • 浏览器报400,JSON格式错误。

      • JSON的名值对中的字符串需要是双引号。写成:data:"{'pageIndex':10}"就是错误的。
      • JSON数据中不可以有回车。最开始我使用JSON.stringify()这个方法处理,但是在IE下各种问题。不是方法行为不一致就是JSON对象不支持等等。后来直接引用了jquery.json.js,使用了他的$.toJSON()方法。

      var jquery_content = $.toJSON(blog_content);

    • 如果使用data:'content=some&uid=1'方式提交数据,需要注意提交内容中是否包含不合适的符号,比如'&'。

  • 相关阅读:
    TensorFlow分布式在Amazon AWS上运行
    在C++中加载TorchScript模型
    java 在 linux 持续运行 并不让其输出日志
    reactor.core.Exceptions$OverflowException: Could not emit tick 1 due to lack of requests (interval doesn't support small downstream requests that replenish slower than the ticks)
    https://gitee.com/createmaker/webflux-r2dbc-demo-pri
    清晨与暮霭 : 清晨,我睁开惺忪得眼睛,望向初升的朝阳,感受温暖. 暮霭,聆听风的私语,感受万籁俱寂.
    https://gitee.com/createmaker/eventbus-demo
    Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
    只是习惯,改掉就好,只是不习惯,习惯了就好
    从游戏角度了解RxJava
  • 原文地址:https://www.cnblogs.com/zhuani21/p/5376690.html
Copyright © 2011-2022 走看看