【发布时间】:2019-03-24 11:16:14
【问题描述】:
我正在使用 Spring 5 MVC 以 JSON 响应使用 JQuery 的请求。
客户端代码是这样的:
$.ajax({
url: 'http://127.0.0.1:8080/spring.MVC.REST.simple-0.0.1-SNAPSHOT/Products.htm',
dataType: 'json',
type: 'GET',
success: function(result){
$('#resultados').html(result);
}
})
请求头是预期的,像这样:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9,en;q=0.8
Connection: keep-alive
Host: 127.0.0.1:8080
Referer: http://127.0.0.1:8080/spring.MVC.REST.simple-0.0.1-SNAPSHOT/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
X-Requested-With: XMLHttpRequest
所以我认为问题出在服务器端。我用的是WildFly 14,响应头是这样的:
Connection: keep-alive
Content-Length: 73
Content-Type: text/html;charset=UTF-8
Date: Fri, 19 Oct 2018 14:09:40 GMT
我试图从服务器发送 Content-Type: appliation/json 但客户端收到 Content-Type: text/html(不接受)。
在服务器中,我有一个控制器。这里我放了一段代码:
@Controller
@RequestMapping("/Products.htm")
public class ProductsController {
@Autowired
private ProductManager productManager;
@RequestMapping(method = RequestMethod.GET,
produces = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE})
@ResponseBody
public List<Product> getProducts() {
return productManager.getProducts();
}
....
我还在 WebConfig 类中有一个 bean 来协商交互 http 之间的内容。这里有一个sn-p代码:
@Configuration
@EnableWebMvc
@ComponentScan("es.foxinet.springapp.web")
public class SpringappWebConfig {
@Bean
public ContentNegotiationManagerFactoryBean
contentNegotiationManager() {
ContentNegotiationManagerFactoryBean negociatorBean = new
ContentNegotiationManagerFactoryBean();
negociatorBean.setFavorPathExtension(false);
negociatorBean.setParameterName("mediaType");
negociatorBean.setFavorParameter(true);
negociatorBean.setIgnoreAcceptHeader(true);
negociatorBean.setUseRegisteredExtensionsOnly(true);
negociatorBean.setDefaultContentType(MediaType.APPLICATION_JSON);
negociatorBean.addMediaType("json", MediaType.APPLICATION_JSON);
negociatorBean.addMediaType("xml", MediaType.APPLICATION_XML);
return negociatorBean;
}
.....
}
我的 Maven pon.xml 文件中还有下一个依赖关系,可以使用 jackson(用于 json)和 JAXB(用于 xml)。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
<scope>runtime</scope>
</dependency>
我做错了什么?
感谢您的帮助。 提前致谢
【问题讨论】:
-
如何让端点网址具有 .htm 扩展名完全令人困惑,但它返回的是 JSON(或 XML),而不是 HTML。
标签: jquery json spring rest model-view-controller