这里我将配置一个BeanNameViewResolver视图解析器,使用视图名称来解析视图
注意点:
在springmvc.xml文件中如果有多个视图解析器,可以进行优先级的设置,order 值越小优先级越高
<span style="font-family:SimSun;font-size:18px;"><!-- 配置一个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></span>1.写一个HelloView类,实现View接口
<span style="font-size:18px;">package com.cgf.springmvc.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()); } }</span>2.再写一个目标方法
<span style="font-size:18px;">package com.cgf.springmvc.handlers; 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"); <strong><span style="color:#000099;">return "helloView";</span></strong> } }</span>这里return的是视图名的第一个字母小写,springmvc会根据这个helloView名,去getBean,得到这个视图对象。
3.在index.jsp中:
<span style="font-size:18px;"><a href="springmvc/testMyView">Test MyView</a><br></span>