在我的春天的webapp,我有一個AJAX的servlet這個問題的答案(使用傑克遜)JSON:春天阿賈克斯 - @ResponseBody - 返回null響應
<?xml version="1.0" encoding="UTF-8"?>
<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:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="com.myapp.ajax" />
<util:list id="messageConvertersList">
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</util:list>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters" ref="messageConvertersList" />
</bean>
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptor>
</mvc:interceptors>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
<bean id="handlerExceptionResolver" class="com.myapp.ajax.AjaxExceptionHandlerResolver">
<property name="exceptionHandler">
<bean class="com.myapp.ajax.AjaxExceptionHandler" />
</property>
<property name="messageConverters" ref="messageConvertersList" />
</bean>
我有以下的AJAX服務:
@RequestMapping(value = "getLoggedUser")
@ResponseBody
public DtoUser getLoggedUser() {
return authenticationService.getLoggedUser();
}
當用戶登錄其返回類似:
{ userName : "jojo", email : "[email protected]", firstName : "John", lastName : "Doe" }
當用戶沒有登錄,預期的行爲是返回
null
但是它返回一個空應答,其不是有效的JSON響應(並另外用壞內容類型報頭)
這是怎麼發生的?
我是否有解決方案來獲得預期的行爲?
我會認爲空的json會是正確的行爲,如果你返回一個空對象,不返回字符串「null」。什麼是作爲內容類型返回?如果您試圖遵循更加REST的模式,最好的解決方案是返回適當的HTTP狀態代碼,如404(未找到)或401(未授權)。或者,更好的是,將它們重定向/轉發到登錄頁面。 – CodeChimp
一個空的json意味着我必須測試一個屬性(例如:response.email)以知道用戶是否爲null。這就是爲什麼我認爲返回null更合適和連貫 –