使用Spring MVC自定义HTTP代码 [英] Custom http code with Spring MVC

查看:152
本文介绍了使用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());
    }
}

希望这会有所帮助.

这篇关于使用Spring MVC自定义HTTP代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆