由于在Spring配置文件中添加了视图解析器,会对Controller返回的字符串进行拼串,因此如果在Controller层要访问和WEB-INF同层的页面如hello.jsp,则比较麻烦。
//视图解析器
<?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 http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.com.czl"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
文件目录:

../../hello通过拼串后,为/WEB-INF/pages/../../hello.jsp,即/hello.jsp(/服务器会解析到项目名目录下)
@RequestMapping("/hello")
public String hello(HttpServletResponse response){
response.setLocale(Locale.US);
System.out.println("正在处理请求...");
return "../../hello";
}
这样子还是比较麻烦的,可以通过前缀进行转发和重定向
package com.czl.controller;
@Controller
public class HelloController {
/**
* forward:转发到一个页面
* /hello.jsp:转发当前项目下的hello;
*
* 一定加上/,如果不加/就是相对路径。容易出问题;
* forward:/hello.jsp
* forward:前缀的转发,不会由我们配置的视图解析器拼串
*
* @return
*/
@RequestMapping("handle01")
public String handle01(){
System.out.println("handle01...");
return "forward:/hello.jsp";
}
@RequestMapping("handle02")
public String handle02(){
System.out.println("handle02....");
return "forward:/handle01";
}
/**
* 重定向到hello.jsp页面
* 有前缀的转发和重定向操作,配置的视图解析器就不会进行拼串;
*
* 转发 forward:转发的路径
* 重定向 redirect:重定向的路径
* /hello.jsp:代表就是从当前项目下开始;在SpringMVC中会为路径自动的拼接上项目名
*
*
* 原生的Servlet重定向/路径需要加上项目名才能成功,
* 重定向的url路径是要发给浏览器让浏览器按照该url访问服务器的,而浏
* 览器解析/ 只到站点,如 localhost:8080/,使用response.sendRedirect("/hello.jsp"),浏览器只会解析为:
* localhost:8080/hello.jsp
*
* response.sendRedirect("/hello.jsp")//访问不到,要加上项目名 /SpringMVC_viewResolver_06/hello.jsp
* @returnrd.include(requestToExpose, response);
*/
@RequestMapping("handle03")
public String handle03(){
System.out.println("handle03...");
return "redirect:/hello.jsp";
}
@RequestMapping("handle04")
public String handle04(){
System.out.println("handle04...");
return "redirect:/handle03";
}
}
在SpringMVC配置中,视图解析器会对Controller返回的字符串路径进行处理,导致访问WEB-INF同级页面时路径需要额外拼接。例如,访问hello.jsp需要转换为'/WEB-INF/jsp/hello.jsp'。为了避免这种繁琐的拼接,可以利用forward:/和redirect:/作为前缀来简化转发和重定向操作。
195





