springmvc 视图管理器

本文介绍了Spring MVC中视图解析器的作用,如何通过配置InternalResourceViewResolver来简化对.jsp页面的访问,避免在路径中手动添加后缀。在web.xml和springmvc.xml中设置DispatcherServlet和视图解析器后缀,使得控制器可以直接返回视图名称,而不需要明确指定后缀。
摘要由CSDN通过智能技术生成

视图解析器:简化开发通常情况下每次访问一个资源比如说 demo.jsp 那么在路径中都要输入.jsp后缀 对于开发人员来说那么如果
有很多.jsp页面那么就需要很多重复的动作,那么有没有一种方法来简化开发那? 视图解析器就可以帮我们解决这种问题;

每当浏览器访问一个action后springmvc都会返回一个ModelAndView对象那么他的依据就是
org.springframework.web.servlet.DispatcherServlet
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- springmvc配置 -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
 
springmvc.xml文件
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
">
<!-- 配置自定扫描的包 -->
<context:component-scan base-package="blog.csdn" />
<!-- 配置注解驱动 -->
<mvc:annotation-driven />
</beans>
没有配置视图解析器之前的访问示例图:


我们发现如果我们没有配置视图解析器,想要跳转到demo.jsp就必须输入".jsp"的后缀

在springmvc.xml中配置视图解析器:
  <!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置视图解析器前缀 -->
<property name="prefix" value="/"></property>
<!-- 配置视图解析器后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>  
修改后的controller

测试:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值