2014-03-03 43 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,建立自己的客户错误响应对象和错误代码