之前两篇博客springMVC源码分析--HandlerMethodReturnValueHandler返回值解析器(1)和 springMVC源码分析--HandlerMethodReturnValueHandlerComposite返回值解析器集合(2)我们分别介绍了返回值处理器相干的东西,接下来我们选取1个简单的实现类ViewNameMethodReturnValueHandler来简单介绍1下返回值处理操作。
1、返回值为jsp页面地址
@RequestMapping(value = "input") public String inputProduct() { logger.info("inputProduct called"); return "jsp/ProductForm"; //对应jsp页面名称 }
实现代码以下:
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { //判断是不是是String类型 if (returnValue instanceof CharSequence) { //如果是将其设置为视图名称 String viewName = returnValue.toString(); mavContainer.setViewName(viewName); if (isRedirectViewName(viewName)) { mavContainer.setRedirectModelScenario(true); } } else if (returnValue != null){ // should not happen throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); } }
ViewNameMethodReturnValueHandler完全源码以下,处理机制还是比较简单的。
//HandlerMethodReturnValueHandler的子类,主要就是Controller履行后返回的视图名称 public class ViewNameMethodReturnValueHandler implements HandlerMethodReturnValueHandler { private String[] redirectPatterns; //设置跳转链接的匹配方式 public void setRedirectPatterns(String... redirectPatterns) { this.redirectPatterns = redirectPatterns; } /** * The configured redirect patterns, if any. */ public String[] getRedirectPatterns() { return this.redirectPatterns; } @Override public boolean supportsReturnType(MethodParameter returnType) { Class<?> paramType = returnType.getParameterType(); return (void.class == paramType || CharSequence.class.isAssignableFrom(paramType)); } //实现逻辑还是比较简单的,就是设置ModelAndViewContainer的viewName视图名称 @Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue instanceof CharSequence) { String viewName = returnValue.toString(); mavContainer.setViewName(viewName); if (isRedirectViewName(viewName)) { mavContainer.setRedirectModelScenario(true); } } else if (returnValue != null){ // should not happen throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); } } //判断返回值是不是是跳转链接,以redirect:开头 protected boolean isRedirectViewName(String viewName) { return (PatternMatchUtils.simpleMatch(this.redirectPatterns, viewName) || viewName.startsWith("redirect:")); } }