[英]How tomcat call the @requestMapping annotation
我是Spring MVC的新手,在瀏覽網上的各種教程時遇到了這個疑問,我遇到了在@requestMapping注解下編寫函數的幾種語法例如。
語法 1: '''
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
''' 語法 2:'''
@RequestMapping(value = "/welcome",method = RequestMethod.GET)
public ModelAndView printer()
{
ModelAndView m = new ModelAndView("hello");
m.addObject("Welcome", "Success !! Krishna");
return m;
}
''' 語法 3:'''
@RequestMapping(value = "/welcome",method = RequestMethod.GET)
public ModelAndView printer(HttpServletRequest request , HttpServletResponse response)
{
//Some code
}
'''
我的問題是:
Tomcat 如何知道我的函數需要哪些參數以及它如何向我的函數提供請求的參數
Tomcat 只提供了HttpServletRequest
和HttpServletResponse
的實際實例(即Servlet
API 中定義的那些對象)。決定和解析參數值的實際工作是由spring-mvc完成的。 然后它使用解析的值調用控制器方法。
它基本上歸結為使用反射 API 來獲取匹配的控制器方法的參數的類型信息(例如其注釋設置、數據類型等)。 基於這些類型信息,它根據docs 中定義的規則解析值。 解析完所有值后,它會再次使用反射 API 以解析的值調用此控制器方法。
偽代碼看起來像:
FooController controller = context.getBean(FooController.class);
Method matchedControllerMethod = findMatchedControllerMethod(controller, httpServletRequest);
int parameterCount = matchedControllerMethod.getParameterCount().
Object[] resolvedParamValues = new Object[parameterCount];
for (int i = 0; i < parameterCount; i++) {
Parameter param = matchedControllerMethod.getParameters(i);
if(param.getType().equals(ModelMap.class)){
resolvedParamValues[i] = Util.getModelMap();
}else if(param.getType().equals(HttpServletRequest.class)){
resolvedParamValues[i] = httpServletRequest;
}else if(param.getType().equals(HttpServletResponse.class)){
resolvedParamValues[i] = httpServletResponse
}else if{
.......
........
}
}
matchedControllerMethod.invoke(controller ,resolvedParamValues);
實際上,代碼比這要花哨得多。 例如,它使用策略模式將那些 if-else 檢查替換為一個名為HandlerMethodArgumentResolver
的抽象。 換句話說,通過查看HandlerMethodArgumentResolver
所有實現,您可以知道它如何解析所有可能情況下的參數。
它與 requestMapping 關系不大,而與負責解密參數類型的 requestParam 關系更大。 閱讀更多: https : //dzone.com/articles/using-the-spring-requestmapping-annotation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.