背景
需要一套干净的Spring+Spring MVC+Mybatis框架,框架写到返回Json的环节报错了。
问题
无法Json,报406
解决
需要配置Json工具包,这里用Jackson
Maven Jackson
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.0</version> </dependency>
工程环境SpringMvc 4.x,不兼容Jackson2.9最新版。这里特应用2.6版本
Spring Mvc配置
<!--Begin:使用Jackson 2.x的配置,需要导入的jar包:jackson-core-xxx.jar、jackson-annotations-xxx.jar、jackson-databind-xxx.jar--> <!--通过处理器映射DefaultAnnotationHandlerMapping来开启支持@Controller注解--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> <!--通过处理器适配器AnnotationMethodHandlerAdapter来开启支持@RequestMapping注解--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <!-- 设置返回字符串编码 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name = "supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- json转换器 --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!--End:使用Jackson 2.x的配置,需要导入的jar包:jackson-core-xxx.jar、jackson-annotations-xxx.jar、jackson-databind-xxx.jar-->
好了,重启不报错(一般就是jar宝冲突),就可以正常接收到@ResponseBody返回的Json了。
以上配置,带来好运,祝好 !
by.沫沫金
我得纯净框架,新模块只需要一个Controller就可以,CRUD一句话全搞定。前台专注Form就行。
时间: 2024-10-08 04:14:12