要自定義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:"開頭時,會使用自定義視圖解析器來解析視圖。