繁体   English   中英

使用Spring MVC请求后接收HTTP状态

[英]Receive the HTTP status after a request with Spring MVC

我正在向服务器发送数据,我想收到HTTP响应状态,以检查此状态并提供适当的视图

   @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";
     }

有什么不对:

HttpStatus status = result.getStatusCode();
if(status == HttpStatus.OK)

请参阅: ResponseEntity JavaDoc。

顺便说一句,你不应该使用==运算符比较字符串,如下所示:

status=="OK"

而是使用以下习语:

"OK".equals(status)

Java中的方法名称也倾向于以小写字母开头。

ResponseEntity对象包含HTTP状态代码。

// 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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM