我试图在安全的上下文中对Spring Rest Web服务api进行ajax跨域post调用。从Jquery我不能设置contentType属性cos,然后我对安全上下文有问题。但是没有spring的contentType,我会收到以下响应:415(不受支持的媒体类型)
Spring控制器:
@RequestMapping(value = "/all", method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('PROF1','SUDO')")
Jquery:
function getAllUsers(){
var obj = {"limit":10,"page":0};
$.ajax({
url:"https://webServerSite/myService/api/v1/user/all",
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
data:obj,
type: "post",
success:function(json){
var str = JSON.stringify(json);
console.log(str);
},
error:function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
有一种方法可以在Spring上禁用contentType检查?我所有的数据都是json,我希望将其设置为默认值,以避免内容类型标头检查。我尝试定义一个自定义消息转换器,并使用以下代码无效:
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
//set path extension to true
configurer.favorPathExtension(true).
//set favor parameter to false
favorParameter(false).
//ignore the accept headers
ignoreAcceptHeader(true).
//dont use Java Activation Framework since we are manually specifying the mediatypes required below
useJaf(false).
defaultContentType(MediaType.APPLICATION_JSON).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("json", MediaType.APPLICATION_JSON);
}
谢谢
您可以使用带有@RequestMapping
字段的consumes
批注指定控制器方法接受的内容类型。对于您的用例,您可以考虑使用以下内容接受所有内容类型:
import org.springframework.http.MediaType;
@RequestMapping(value = "/all", method = RequestMethod.POST, consumes = {MediaType.ALL_VALUE})