springMVC的控制器,也就是@Control类中的方法默认返回String类型的一个url地址,可以在操作完成后直接跳到指定页面。然而在大部分开发过程中前后端是分离的,后端研发人员并不清楚前端是什么页面。这时候我们就需要将运行结果以JSON数据返回。前端在想要输出数据的位置获取后端返回的JSON,便完成了一整套WEB开发。
1.准备JSON支持的JAR包(这里使用的fastJson)
fastjson-1.2.31.jar
2.配置spring-mvc.xml(spring配置文件有些是applicationContext.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
</bean>
<!--<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>-->
<!-- 配置Fastjson支持 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter" p:charset="UTF-8">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
<value>WriteDateUseDateFormat</value>
<value>WriteEnumUsingToString</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
3.接下来就是在@Control类中使用@Response标注。
这里写代码片
@Controller
@RequestMapping("/marker")
public class MarkerHandleControl {
@Resource(name="markerHandleServiceImp")
private MarkerHandleServiceImp markerHandleService;
@ResponseBody
@RequestMapping("/insert")
public Object insert(float pointX,float pointY,HttpServletRequest request) {
JSONObject jsonObject=new JSONObject();
if(markerHandleService.insertMarker(marker)) {
//返回{result:1}
jsonObject.put("result", 1);
}else {
//返回{result:0}
jsonObject.put("result", 0);
}
return jsonObject;
}
}
这里是我实现功能的一部分代码。需要注意的就是返回方法返回类型应该设置为Object类型或者JsonObject类型。
如果有相关问题,欢迎留言提问。