要自定义ModelAndView的视图解析,可以通过实现ViewResolver接口来自定义视图解析器。以下是一个简单的示例:
public class CustomViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
if (viewName.startsWith("custom:")) {
return new CustomView(viewName.substring(7));
}
return null;
}
}
public class CustomView extends AbstractUrlBasedView {
public CustomView(String url) {
setUrl(url);
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 自定义视图渲染逻辑
response.getWriter().write("Custom View: " + getUrl());
}
}
<bean id="viewResolver" class="com.example.CustomViewResolver"/>
通过以上步骤,就可以实现自定义ModelAndView的视图解析,当视图名称以"custom:"开头时,会使用自定义视图解析器来解析视图。