How to know which param of @RequestMapping is call

2019-02-27 01:40发布

This is my @RequestMapping annotation:

  @RequestMapping({"/loginBadCredentials", "/loginUserDisabled", "/loginUserNumberExceeded"})
  public String errorLogin(...){        
            ... 
        }

Inside the method errorLogin , is there a way to know which of the three url was "called"?

3条回答
2楼-- · 2019-02-27 02:02

Simplest method is to inject HttpServletRequest and get the uri:

@RequestMapping({"/loginBadCredentials", "/loginUserDisabled", "/loginUserNumberExceeded"})
public String errorLogin(HttpServletRequest request) {        
        String uri = request.getRequestURI(); 
        // switch on uri what you need to do
}
查看更多
我只想做你的唯一
3楼-- · 2019-02-27 02:14

you can inject the HttpServletRequest into the method-parameters and then get the called uri.

  @RequestMapping({"/loginBadCredentials", "/loginUserDisabled", "/loginUserNumberExceeded"})
  public String errorLogin(HttpServletRequest request) {        
            String uri = request.getRequestURI(); 
            // do sth with the uri here
  }
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-02-27 02:18

Add HttpServletRequest as your parameters and use it to find the current request path.

Update: Spring also provides RequestContextHolder:

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
String currentReqUri = attributes.getRequest().getRequestURI();

In my opinion, first approach is better and a little more testable.

查看更多
登录 后发表回答