下面我们来分析如何自定义一个视图,
1、自定义一个实现View接口的类,添加@Component注解,将其放入SpringIOC容器,如下所示:
package com.jd.view;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;
@Component // 将自定义视图放入IOC容器中
public class ToView implements View{
public String getContentType() {
return "text/html";
}
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.getWriter().print("Hello World.");
}
}
2、配置视图解析器,使用视图名字解析视图,如下所示:
<!-- 配置BeanName视图解析器:使用视图名字解析视图 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<!-- order属性用于设定视图解析器的优先级,order值越小优先级越高,InternalResourceViewResolver优先级为Integer所能表示的最大值 -->
<property name="order" value="0"></property>
</bean>
package org.springframework.web.servlet.view;
import java.util.Locale;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.web.context.support.WebApplicationObjectSupport;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
public class BeanNameViewResolver extends WebApplicationObjectSupport implements ViewResolver, Ordered {
//实现了ViewResolver接口
private int order = Integer.MAX_VALUE; // default: same as non-Ordered
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public View resolveViewName(String viewName, Locale locale) throws BeansException {
// 解析视图
ApplicationContext context = getApplicationContext();
if (!context.containsBean(viewName)) {
if (logger.isDebugEnabled()) {
logger.debug("No matching bean found for view name '" + viewName + "'");
}
// Allow for ViewResolver chaining...
return null;
}
if (!context.isTypeMatch(viewName, View.class)) {
if (logger.isDebugEnabled()) {
logger.debug("Found matching bean for view name '" + viewName +
"' - to be ignored since it does not implement View");
}
// Since we're looking into the general ApplicationContext here,
// let's accept this as a non-match and allow for chaining as well...
return null;
}
return context.getBean(viewName, View.class);// 根据视图名直接从IOC容器中获取视图对象
}
}
发布Java Web项目—>执行DispatcherServlet类onRefresh(ApplicationContext context)方法—>执行DispatcherServlet类initStrategies(ApplicationContext context)方法—>执行DispatcherServlet类initViewResolvers(ApplicationContext context)方法ÿ