我創建了一個spring應用程序,當我打開以下鏈接時,它運行成功:localhost:8080/test/greeting。服務器已經完全部署,但是當我打開該鏈接時,一個名爲greeting
的文件被下載,並且內部集成了json。我試圖在Internet Explorer上打開鏈接,並且我認爲json會直接顯示在屏幕上。這不是這種情況嗎?Spring rest json輸出
這裏是調度的servlet:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="test" />
<mvc:annotation-driven />
</beans>
這裏是web.xml中:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
這裏是GreetingController代碼:
package test;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public @ResponseBody Greeting greeting(
@RequestParam(value="name", required=false, defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
我一直在尋找一段時間,並沒有能夠找到解決辦法。
你能顯示控制器代碼嗎? –
我認爲Spring(mvc)返回的響應Content-Type不正確。它應該是「application/json」。搜索「Spring mvc內容類型」。 [這溢出Q/A](http://stackoverflow.com/questions/8951534/spring-mvc-3-return-content-type-text-plain)可能會幫助你。它建議用'@ ResponseBody'註釋你的servlet並使用'response.setContentType'。 – erny
發佈處理該請求的控制器 –