2014-03-03 44 views
0

我使用下面的代碼來處理使用Spring MVC的其他調用。Spring MVC的自定義http代碼

@RequestMapping(value = "login", method = RequestMethod.GET) 
public @ResponseBody 
User login(@RequestParam String username, @RequestParam String password) { 
    User user = userService.login(username, password); 
    if (user == null) 
     ... 
    return user; 
} 

我想發送錯誤的用戶名,密碼錯誤,密碼更改和密碼過期條件的客戶端客戶http代碼。如何修改現有代碼以將這些錯誤代碼發送給客戶端?

回答

1

一種方法是添加一些額外的類來返回HTTP錯誤。你的代碼看起來是這樣的:

@RequestMapping(value = "login", method = RequestMethod.GET) 
@ResponseBody 
public User login(@RequestParam String username, @RequestParam String password) { 
    User user = userService.login(username, password); 
    if (user == null) 
     throw new UnauthorizedException(); 
    return user; 
    } 
} 

@ResponseStatus(value = HttpStatus.UNAUTHORIZED) 
public class UnauthorizedException extends RuntimeException{ 
} 

在這種情況下,用戶會得到401響應狀態代碼

我希望它能幫助

6

您可以使用控制器建議例外控制器內拋出映射到某個特定的客戶端數據在運行時。 例如,如果用戶沒有發現,你的控制器應拋出一些異常(定製或存在一個)

@RequestMapping(value = "login", method = RequestMethod.GET) 
@ResponseBody 
public User login(@RequestParam String username, @RequestParam String password) { 
    User user = userService.login(username, password); 
    if (user == null) 
     throw new UserNotFoundException(username); //or another exception, it's up to you 
    return user; 
    } 
} 

就應該添加@ControllerAdvice,將捕獲控制器的異常並進行「例外到狀態」映射(優點:你將有'異常到狀態映射'的單一責任點):

@ControllerAdvice 
public class SomeExceptionResolver { 

    @ExceptionHandler(Exception.class) 
    public void resolveAndWriteException(Exception exception, HttpServletResponse response) throws IOException { 

     int status = ...; //you should resolve status here 

     response.setStatus(status); //provide resolved status to response 
     //set additional response properties like 'content-type', 'character encoding' etc. 

     //write additional error message (if needed) to response body 
     //for example IOUtils.write("some error message", response.getOutputStream()); 
    } 
} 

希望這會有所幫助。

0

您可以返回HTTP 500或您選擇的代碼(來自org.springframework.http.HttpStatus枚舉),並使用自定義錯誤來模擬JSON響應內的SOAP錯誤。

例如:

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) 
@ExceptionHandler(YourTargetException.class) 
@ResponseBody 
Fault caughtYourTargetException(HttpServletRequest req, Exception ex) { 

    String code = ex.getClass().getName(); 
    String reason = "Caught YourTargetException." 
    return new Fault(code, reason); 
} 

Fault類可以是這個樣子(通過http://www.w3.org/TR/soap12-part1/#soapfault啓發):

/** 
* A Fault is an object that can be serialized as JSON when expected errors occur. 
*/ 
public class Fault { 

    @JsonProperty("faultCode") 
    private final String code; 

    @JsonProperty("faultReason") 
    private final String reason; 

    @JsonProperty("faultDetails") 
    private final List<String> details = new ArrayList<>(); 

    public Fault(String code, String reason) { 
    this.code = code; 
    this.reason = reason; 
    } 

    public Fault(String code, String reason, String... detailEntries) { 
    this.code = code; 
    this.reason = reason; 
    details.addAll(Arrays.asList(detailEntries)); 
    } 

    public String getCode() { 
     return code; 
    } 

    public String getReason() { 
     return reason; 
    } 

    /** 
    * Zero or more details may be associated with the fault. It carries 
    * additional information relative to the fault. For example, the Detail 
    * element information item might contain information about a message 
    * not containing the proper credentials, a timeout, etc. 
    * @return Zero or more detail entries. 
    */ 
    public Iterable<String> getDetails() { 
     return details; 
    } 

    @Override 
    public String toString() { 
     return String.format("Fault %s occurred. The reason is %s.", getCode(), 
      getReason()); 
    } 
} 

你可以使用Java框架現有SOAPFaults之一,但我有發現它們在REST中表現不佳。創建我自己的簡單版本變得更簡單。

0

您可以定義自己的狀態碼並返回對象。在你的代碼拋出自定義異常,然後定義異常處理程序如下:

@ControllerAdvice 
public class GlobalControllerExceptionHandler { 

@ExceptionHandler(MyException.class) 
public ResponseEntity<MyRetObject> handleControllerError(HttpServletRequest req, MyException ex) { 
    LOG.warn("My error", ex); 
    MyRetObject errorMessage = new MyRetObject(ex.getMessage()); 
    return ResponseEntity.status(600).body(errorMessage); 
} 

}

在你的情況替換MyExeption.class通過UserNotFoundException.class,建立自己的客戶錯誤響應對象和錯誤代碼