自定义视图和视图解析器的步骤:

  1).编写自定义的视图解析器,和视图实现类。

    自定义的视图要实现View对象

public class MyView implements View{

	@Override
	public String getContentType() {
		return "text/html";
	}

	@Override
	public void render(Map<String, ?> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		List<String> novels = (List<String>) model.get("novel");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("哈哈<br/><h1>欢迎阅读四大名著</h1></br>");
		for(String n:novels){
			response.getWriter().write(n+"<br/>");
		}
	}
	
}

  自定义的视图解析器要实现ViewResolver对象,如果配置了多个视图解析器,可以通过实现Ordered接口,设置视图解析器的优先级。

public class MyViewResolver implements ViewResolver, Ordered{

	private Integer order = 0;
	
	@Override
	public View resolveViewName(String viewName, Locale locale)
			throws Exception {
		if(viewName.startsWith("novel:")){
			return new MyView();
		}else{
			return null;
		}

	}

	@Override
	public int getOrder() {
		return order;
	}
	
	public void setOrder(Integer order){
		this.order = order;
	}

}

2).视图解析器放在ioc容器中。

 

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/WEB-INF/pages/"></property>
			<property name="suffix" value=".jsp"></property>
		</bean>
		
		<!-- order越小,优先级越大 -->
		<bean class="com.view.MyViewResolver">
			<property name="order" value="0"></property>
		</bean>