使用Spring MVC自定义HTTP代码
我使用以下代码使用Spring MVC处理其他调用.
I use the following code to handle rest calls using Spring MVC.
@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代码,用于输入错误的用户名,错误的密码,更改的密码和密码过期的条件.如何修改现有代码以将这些错误代码发送给客户端?
I would like to send the client customer http codes for wrong username, wrong passwords, password changed and password expire conditions. How can I modify the existing code to send these error codes to the client?
您可以使用控制器建议在运行时将控制器内引发的异常映射到某些客户端特定的数据. 例如,如果未找到用户,则您的控制器应引发一些异常(自定义或存在的异常)
You can use controller advice to map exception thrown within controller to some client specific data at runtime. For example if user is not found, your controller should throw some exception (custom or existed one)
@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,它将捕获控制器异常并进行异常到状态"映射(优点:您将对异常到状态映射"负有单一责任):
Then you should add @ControllerAdvice that will catch controller exceptions and make 'exception-to-status' mapping (pros: you will have single point of responsibility for 'exception-to-status-mapping'):
@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());
}
}
希望这会有所帮助.