我尝试从我的Web服务获取对象时会得到以下异常:
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"html"). Expected elements are <{}user>
用户类用@XmlRootElement
注释,通过浏览器显示XML表示用户
客户端代码(我使用MediaType.TEXT_HTML
,因为MediaType.APPLICATION_XML
原因RestClientException
):
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
Jaxb2RootElementHttpMessageConverter jaxbMessageConverter = new Jaxb2RootElementHttpMessageConverter();
List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.TEXT_HTML);
jaxbMessageConverter.setSupportedMediaTypes(mediaTypes);
messageConverters.add(jaxbMessageConverter);
restTemplate.setMessageConverters(messageConverters);
User x = restTemplate.getForObject("http://localhost:8080/Online_Shopping/dispatcher/rest/hello",User.class);
Web服务代码:
@Controller
@RequestMapping(value = "/rest")
public class RESTController {
@RequestMapping(value = "/hello",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_XML_VALUE)
public @ResponseBody User getUser() {
return new User("paymon","123",true);
}
}
事实证明,由于安全拦截器,我无法访问Web服务。<intercept-url pattern="/dispatcher/rest/**" access="hasRole('ROLE_ADMIN')"/>
评论了拦截器后,我的Web服务正常工作。唯一的问题是我想知道如何保护我的Web服务以通过Java代码访问它。