How to know which param of @RequestMapping is called

孤街醉人 提交于 2019-12-02 02:46:39

问题


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"?


回答1:


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.




回答2:


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
  }



回答3:


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
}


来源:https://stackoverflow.com/questions/34919809/how-to-know-which-param-of-requestmapping-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!