本文介绍了使用Spring MVC请求后接收HTTP状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在向服务器发送数据,我希望收到HTTP响应状态以检查此状态并提供相应的视图
i'm sending data to a server and i want to receive the HTTP response status in order to check this status and provide the appropriate view
@RequestMapping(method = RequestMethod.POST)
public String Login(@ModelAttribute("Attribute") Login login, Model model,HttpServletRequest request) {
// Prepare acceptable media type
ArrayList<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<Login> entity = new HttpEntity<Login>(login, headers);
// Send the request as POST
try {
ResponseEntity<Login> result = restTemplate.exchange("http://www.../user/login/",
HttpMethod.POST, entity, Login.class);
} catch (Exception e) {
}
//here i want to check the received status
if(status=="OK"){
return "login"
}
else
return "redirect:/home";
}
推荐答案
对象包含HTTP状态代码。
The ResponseEntity object contains the HTTP status code.
// Prepare acceptable media type
ArrayList<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<Login> entity = new HttpEntity<Login>(login, headers);
// Create status variable outside of try-catch block
HttpStatus statusCode = null;
// Send the request as POST
try {
ResponseEntity<Login> result = restTemplate.exchange("http://www.../user/login/",
HttpMethod.POST, entity, Login.class);
// Retrieve status code from ResponseEntity
statusCode = result.getStatusCode();
} catch (Exception e) {
}
// Check if status code is OK
if (statusCode == HttpStatus.OK) {
return "login"
}
else
return "redirect:/home";
这篇关于使用Spring MVC请求后接收HTTP状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!