在上一实例中,我们访问hello.jsp页面是通过自定义的控制器,因为我们配置了viewresolver将jsp页面隐藏在了WEB-INF下面,这时页面不能通过url直接访问。如果我们想直接访问某个页面而不需要自定义控制器,则需要进行如下配置:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
classpath:/org/springframework/context/config/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
classpath:/org/springframework/web/servlet/config/spring-mvc-3.2.xsd ">
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="indexController.do">indexController</prop>
</props>
</property>
</bean>
<!-- 用于页面跳转 -->
<bean id="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="index"/>
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<!-- 返回的视图模型数据需要经过jstl来处理 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
当访问indexController.do时,则会跳转到/WEB-INF/jsp/index.jsp文件
显然上面的方法存在一个不足之处,当我们直接跳转的页面比较多时,每配置一个,就需要添加一个bean;下面有中更简洁的方法:
配置如下:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
classpath:/org/springframework/context/config/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
classpath:/org/springframework/web/servlet/config/spring-mvc-3.2.xsd ">
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.do">indexController</prop>
</props>
</property>
</bean>
<!-- 用于页面跳转,根据请求的不同跳转到不同页面,如请求index.do则跳转到/WEB-INF/jsp/index.jsp页面 -->
<bean id="indexController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<!-- 返回的视图模型数据需要经过jstl来处理 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
当我们想访问/WEB-INF/jsp下面的login.jsp页面时,我只需要在SimpleUrlHandlerMapping中添加<prop key="login.do">indexController</prop>即可。