一,示例
1,在handler类中添加方法如下:
//重定向
@RequestMapping("/testRedirect")
public String testRedirect() {
System.out.println("testRedirect");
return "redirect:/index.jsp";
}
二,源码解析
1,进入DispatcherServlet的doDispatch方法
2,找到视图mv
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
3,进入processDispatchResult方法
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
4,进入渲染视图 方法为render
render(mv, request, response);
5,进入解析视图 方法为resolveViewName
view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);
6,再进入如下代码中的resolveViewName,是一个接口
View view = viewResolver.resolveViewName(viewName, locale);
7,找到resolveViewName接口的实现类AbstractCachingViewResolver
8,进入创建视图 createView方法 是一个抽象类,找到他的继承子类UrlBasedViewResolver
return createView(viewName, locale);
9,createView的继承子类UrlBasedViewResolver分析
在UrlBasedViewResolver的createView方法中可以看到如下代码
//如果返回名字是以redirect开头就返回一个redirect视图,如果返回名字以forWord开头就返回InternalResourceView视图
if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length());
RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());
return applyLifecycleMethods(viewName, view);
}
// Check for special "forward:" prefix.
if (viewName.startsWith(FORWARD_URL_PREFIX)) {
String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length());
return new InternalResourceView(forwardUrl);
}