SpringMVC-转发和重定向
SpringMVC实现转发和重定向无需视图解析器
步骤:这里我只写出变化的代码。
没用视图解析器
- 创建项目
- 添加web支持,手动导入lib
- 配置web.xml
- 配置
springmvc-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描指定包,让指定包下的注解生效 -->
<context:component-scan base-package="controller"/>
<!-- 让springMVC不处理静态资源 -->
<mvc:default-servlet-handler/>
<!-- 开启MVC注解支持 -->
<mvc:annotation-driven/>
</beans>
- 编写业务控制类(转发有两种方式,重定向有一种方式)
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/c")
public class controllerDemo {
//转发
@RequestMapping("/t1")
public String test1(){
//方式一:
return "/index1.jsp";
}
@RequestMapping("/t2")
public String test2(){
//方式二
return "forward:/index1.jsp";
}
//重定向
@RequestMapping("/t3")
public String test3(){
return "redirect:/index1.jsp";
}
}
- 编写跳转的
index1.jsp
(不能放在WEB-INF下,放在WEB-INF下,要修改路径)
<%--
Created by IntelliJ IDEA.
User: 碎碎念
Date: 2021/3/28
Time: 16:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>index1.jsp</h1>
</body>
</html>
用了视图解析器
变化的就是controller的代码,还有在springmvc-servlet.xml配置视图解析器
controller代码:
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/c")
public class controllerDemo {
//有视图解析器
//转发
@RequestMapping("/t4")
public String test4(){
return "index1.jsp";
}
//重定向
@RequestMapping("/t5")
public String test5(){
return "redirect:/index1.jsp";
}
}
运行结果:
转发会发生404错误,重定向没事,重定向照样执行