实现ssm整合下的controller接口(用于整合Vue的步骤之一)
1.修改pom文件,添加异步通信的依赖
2.修改spring配置文件
3.在controller的方法内添加注解@ResponseBody
//这个是会返回json的
1.pom文件如下
<!--jie解决ajax交互依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.4</version>
</dependency>
2.spring配置文件内要添加的内容
<context:annotation-config />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!--json转换器-->
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text"/>
<constructor-arg index="1" value="plain"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="*"/>
<constructor-arg index="1" value="*"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text"/>
<constructor-arg index="1" value="*"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application"/>
<constructor-arg index="1" value="json"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
</list>
</property>
</bean>
3.具体例子
(controller内怎么写)
@RequestMapping(value = "getJson", method = RequestMethod.GET)
@ResponseBody
public Map getJson(HttpSession httpSession){
Map<String,Object> map = new HashMap<String, Object>();
List<Category> cs = new LinkedList<Category>();
cs.add(new Category());
cs.add(new Category());
cs.add(new Category());
cs.add(new Category());
try {
map.put("errorCode", 0);
map.put("message", "hello");
map.put("cs",cs);
} catch (Exception e) {
map.put("errorCode", 1);
map.put("errorMessage", "未知错误");
}
System.out.println("已经进入controllor");
System.out.println("已经设置返回了");
return map;
}
最后,前后端分离还会涉及到跨域问题,还需要前端做请求拦截并且转换或者后台做过滤处理。