SpringMVC- Forward and redirect
SpringMVC implements forwarding and redirectionNo view resolver required
Steps: HERE I just write the code that changes.
No view resolver
- Create a project
- Add Web support to manually import lib
- Configure web. XML
- configuration
springmvc-servlet.xml
<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">
<! -- Scan the specified package to validate the annotations under the specified package -->
<context:component-scan base-package="controller"/>
<! Let springMVC not handle static resources -->
<mvc:default-servlet-handler/>
<! -- Enable MVC annotation support -->
<mvc:annotation-driven/>
</beans>
Copy the code
- Write a business control class (there are two ways to forward and one way to redirect)
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/c")
public class controllerDemo {
/ / forwarding
@RequestMapping("/t1")
public String test1(a){
// Method 1:
return "/index1.jsp";
}
@RequestMapping("/t2")
public String test2(a){
2 / / way
return "forward:/index1.jsp";
}
/ / redirection
@RequestMapping("/t3")
public String test3(a){
return "redirect:/index1.jsp"; }}Copy the code
- Programmed to jump
index1.jsp
(can’t put in web-INF, put in web-INF, need to change path)
<%-- Created by IntelliJ idea. User: Created by 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>
Copy the code
The view resolver is used
What has changed is the controller code and the configuration of the view parser in SpringMVC-servlet.xml
The controller code:
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/c")
public class controllerDemo {
// There is a view resolver
/ / forwarding
@RequestMapping("/t4")
public String test4(a){
return "index1.jsp";
}
/ / redirection
@RequestMapping("/t5")
public String test5(a){
return "redirect:/index1.jsp"; }}Copy the code
Running results:
Forwarding error 404, redirection is fine, redirection will continue