一、文章描述:
本文介绍Spring MVC中使用关键字forward和redirect进行页面的跳转,并总结使用关键字forward和redirect注意点!
二、简单代码说明
(1)forward关键字
@Controller
public class UserController {
@RequestMapping("/welcome")
public String welcome(){
//forward关键字转发页面
return "forward:/WEB-INF/jsp/welcome.jsp";
}
}
说明:前端页面发来一个"/welcome"请求,然后跳转到WEB-INF目录下的jsp文件夹的welcome.jsp。
(2)redirect关键字
@Controller
public class UserController {
@RequestMapping("/welcome")
public String welcome(){
//redirect关键字重定向
return "redirect:/welcome1.jsp";
}
}
说明:前端页面发来一个"/welcome"请求,然后重定向到webapp目录下的welcome1.jsp。
springmvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.controller"></context:component-scan>
<!--视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 视图解析对象解析跳转文件所在目录-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 文件的后缀名-->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
三、个人总结
注意点:
1.使用关键字,Spring MVC的配置文件中的视图解析器的对象不生效,不能根据配置的路径和文件后缀名自动跳转。
2.重定向只能访问webapp根目录下的文件,只有程序内部转发的时候才能转发到WEB-INF下的JSP。
3.若使用关键字跳转页面,例如:“redirect: /welcome” 不添加后缀名,则访问的是controller的映射路径,而不是跳转到welcome.jsp页面。
?希望以上的分享对你有所帮助!若有错误,请小伙伴们指出!
版权声明:本文为qq_43647384原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。