原本今年打算研究一下springcloud,可是公司的項目一個接着一個,時間飛逝2019都已接近尾聲,項目也都接近了尾聲,終於可以研究一下自己喜歡的東西了。
直切主題:
瀏覽器請求Eureka接口默認返回的是xml原因是:
然後解決辦法:
導入依賴:
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
</dependency>
如果不導入依賴,後臺只支持後綴爲json的請求地址,而不支持.xml
然後你去瀏覽器輸入url會報404:
這樣寫後臺肯定是將.後面的也當作實際路徑了,所以報404,這時候我們需要配置一下 WebMvcConfigurer:
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
/**
* setUseSuffixPatternMatch : 設置是否是後綴模式匹配,如“/user”是否匹配/user.*,默認真即匹配;
* setUseTrailingSlashMatch : 設置是否自動後綴路徑模式匹配,如“/user”是否匹配“/user/”,默認真即匹配
* @param configurer
*/
@Override
protected void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(true)
.setUseTrailingSlashMatch(true);
}
}
讓他可以匹配後綴
給你們看下我得controller,我直接在啓動類裏面寫的
@RestController
@EnableEurekaClient
@SpringBootApplication
@ComponentScan
public class Consumer2Application {
public static void main(String[] args) {
SpringApplication.run(Consumer2Application.class, args);
}
/**
* @return
*/
@GetMapping(value = "/ziDing")
public User getJX(@RequestParam Long id) {
User user = new User();
user.setId(id);
user.setFrom("自定義");
user.setUserName("張學偉i");
return user;
}
}
然後是請求效果圖:
這種就是根據請求的url後綴決定返回格式,需要注意的是url後面加後綴而不是參數後面加後綴
====================================================================================
下面介紹如何指定返回固定格式
xml:
在controller上的RequestMapping中加上produce
@RequestMapping(produces = MediaType.APPLICATION_ATOM_XML_VALUE)
效果如下:
然後是json:
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
好了有疑問的小夥伴可以給我留言,基本上1天就會回覆