最近阅读spring官方文档的时候,接触到了一些关于MVC命名空间下的一些属性,查看学习官方文档后记录下下来方便以后的学习;首先我来看一下view-controller这个属性是用来干什么的。
先来看一段代码,下面这段代码的作用是在Controller中实现一个页面的跳转功能。
@Controller
@RequestMapping("index")
public class TestController {
/**
* @Title: toIndex
* @Description: 实现页面跳转功能
* @return
*/
@RequestMapping("toIndex")
public String toIndex(){
return "index";
}
}
在平常的开发过程中我们经常使用这种方式来实现页面之间的跳转,这样的没有任何业务逻辑的页面跳转功能,需要我们定义一个请求类或请求方法来实现这一功能,页面跳转管理起来比较混乱,并且每个Controller类中都有分布,查找起来比较困难、浪费时间。
基于对上面的代码的分析,我想到了使用mvc命名空间中的view-controller这个属性来定义这样的一个页面跳转功能。
使用<mvc:view-controller path="" view-name=""/>方式配置页面的跳转,配置如下:
<mvc:view-controller path="/index/toIndex.do" view-name="index"/>
path:指的是请求的路径,
view-name:返回的视图名字(视图解释器 配置的文件目录的名字)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<mvc:view-controller path="/index/toIndex.do" view-name="index"/>
<!-- 视图解释器 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
上面在xml中的配置方式,可以省去了代码的编写,可以把相同模块的页面跳转统一的放在一起,进行这个得配置,方便以后的管理。
<mvc:view-controller path="" view-name=""/>也可以通过程序进行配置,通过项目启动的时候加载 path和view-name的映射关系
@Configuration
@EnableWebMvc
public classWebConfig extendsWebMvcConfigurerAdapter {
@Override
public voidaddViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index/toIndex.do").setViewName("index");
}
}
上面这个中程序配置方式生效的前提是@Configuration 这个注解必须生效,可以使用<context:component-scan base-package="" />加载这个类中的注解。