Spring 有一个叫做 Suffix Strategy 的东西,它使框架能够直接从 URL 检查路径扩展以确定输出内容类型。
您看到的编码结果是因为@RequestMapping 被设置为/result.json 并带有.json 扩展名,所以结果作为Json 对象返回。
要解决此问题,您有多种选择。
选项 1:
在您的 Javascript 中将返回的响应作为 Json 对象处理。
选项 2:
将 @RequestMapping 值重命名为 /result。下面是一个代码示例:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@CrossOrigin(origins = "*")
@RequestMapping(value="/result")
public @ResponseBody String sayHello() {
String website = "http://stackoverflow.com";
int count = 4;
String keyword = "keyword";
return "Found \"" + keyword + "\" '" + count + "' times at \"" + website + "\"";
}
}
Javascript(此处添加接受标头是可选的)
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("/result",{headers: { 'Accept': 'text/plain' }})
.then(function(response) {
$scope.result = response.data;
});
});
</script>
选项 3
将@RequestMapping 值保留为/result.json,但使用WebMvcConfigurerAdapter 禁用后缀策略。下面是一个代码示例
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@CrossOrigin(origins = "*")
@RequestMapping(value="/result.json", method = RequestMethod.GET, produces="text/plain")
public @ResponseBody String sayHello() {
String website = "http://stackoverflow.com";
int count = 4;
String keyword = "keyword";
return "Found \"" + keyword + "\" '" + count + "' times at \"" + website + "\"";
}
}
WebMvcConfigurerAdapter 类
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false)
.favorParameter(false)
.ignoreAcceptHeader(false)
.useJaf(false)
.defaultContentType(MediaType.TEXT_PLAIN);
}
}
Javascript
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("/result.json",{headers: { 'Accept': 'text/plain' }})
.then(function(response) {
$scope.result = response.data;
});
});
</script>