BeanNameViewResolver:这个视图解析器跟XmlViewResolver有点类似,也是通过把返回的逻辑视图名称去匹配定义好的视图bean对象。它要求视图bean对象都定义在Spring的application context中,而XmlViewResolver是在指定的配置文件中寻找视图bean对象
1. 在SpringMVC配置文件中添加BeanNameViewResolver
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order" value="10" /> </bean> <!-- 配置视图解析器 --> <!--该视图解析器的order值为Integer.MAX_VALUE --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean>
2. 创建一个HelloView类,实现View接口
import java.util.Date; 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 public class HelloView implements View{ public String getContentType() { // TODO Auto-generated method stub return "text/html"; } public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub response.getWriter().print("Welcome to View:"+new Date()); } }
3. 创建控制器
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping(value="/springmvc") @Controller public class MyView { @RequestMapping(value="/testMyView") public String testView(){ System.out.println("testView"); return "helloView"; } }
这里return的是视图名的第一个字母小写,springmvc会根据这个helloView名,去getBean,得到这个视图对象