配置视图解析器:
我们在指定视图的时候路径是有重复的,重复的操作可以用视图解析器,让框架帮我们:
mv.setViewName("/WEB-INF/view/show.jsp"); mv.setViewName("/WEB-INF/VIEW/other.jsp");
在springmvc配置文件中:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--声明组件扫描器-->
<context:component-scan base-package="com.lifang.controller"/>
<!--声明springmvc框架中的视图解析器,设置视图文件的路径-->
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀,视图文件的路径-->
<property name = "prefix" value = "/WEB-INF/view/"/>
<!--后缀,视图文件的扩展名-->
<property name = "suffix" value = ".jsp"/>
</bean>
</beans>
改进后的代码:
@Controller
public class MyController {
@RequestMapping(value = {"/some.do","/first.do"}) // value = "/some.do"
public ModelAndView doSome(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","欢迎使用Springmvc做web开发");
mv.addObject("fun","执行的是doSome方法");
//show是视图文件的逻辑名称 (文件名称)
mv.setViewName("show");
return mv;
}
}