Comprehensive example explanation of SpringMVC (use examples to help you learn SpringMVC)

Table of contents

Preface

1. Common annotations for SpringMVC

1. Annotation

2. Extension

3. Demonstration of the role of annotations

Import slf4j related dependencies and configuration projects

 pom.xml file

2. Parameter transfer

1. Basic type + String type

test code

Test Results

page

console

2. Complex types

test code

Test Results

page

console

Edit

3. @RequestParam

test code

Test Results

Result one:

Result two:

Result three:

4. @PathVariable

test code

Test Results

page

 console output

 5.@RequestBody

Import @RequestBody dependency

test code

 Third-party software testing operations

Console output

 6. @RequestHeader

test code

Third-party testing operations

 Console output

 3. Method return value

Case 1: void

With the help of tools

Test code

Test results (results displayed on the page)

Case 2: String

Case 3: String+model

jsp file code

 test code

Run test results

 Case 4: ModelAndView

test code

jsp file

Test Results

 4. Page jump

test code

Scenario 1: (Forwarded to a certain method in the background (current class))

Test Results

Scenario 2: (Forwarded to a certain method in the background (other classes))

Test Results

Scenario 3: (Redirect to a certain method in the background (current class))

Test Results

Scenario 4: (Redirect to a certain method in the background (other classes))

Test Results

in conclusion


Preface

In the last blog, we had a preliminary understanding of some basic knowledge of the SpringMVC framework, and also experienced some of the help and benefits that the SpringMVC framework has given us in development. In today’s blog, all veterans will follow me and continue to learn about SpringMVC. Knowledge.

1. Common annotations for SpringMVC

1. Annotation

  1. @Controller : Used to identify a class as a SpringMVC controller, which receives user requests and returns corresponding views or data .

  2. @RequestMapping : The processing method used to map the requested URL path to the controller. Can be used at class level and method level to handle various HTTP requests (GET, POST, PUT, etc.) .

  3. @RequestParam : Used to bind request parameters to parameters of the processing method. You can specify the name of the parameter, whether it is required, and its default value.

  4. @PathVariable : used to bind placeholder parameters in the URL to parameters of the processing method. Typically used for RESTful style URLs.

  5. @ResponseBody : Used to return the return value of the method directly to the client as the content of the HTTP response. Suitable for returning data in non-HTML formats such as JSON and XML .

  6. @ModelAttribute : used to bind request parameters to an object and add the object to the model, which can be obtained in the view.

  7. @RequestHeader : The annotation can obtain the specified request header information.

  8. @CookieValue : Mainly maps the requested cookie data to the parameters of the function processing method.

2. Extension

springMVC annotations
annotation illustrate
@GetMapping Mapping to handle get request
@PostMapping Mapping for processing post request
@PutMapping: Mapping for processing put request
@DeleteMapping Mapping to handle delete request
@RequestMapping(method=RequestMethod.GET) It maps get to a specific method

3. Demonstration of the role of annotations

The scope of action of springMVC annotations
field Function description
Request mapping Specify the mapping relationship between the URL path and the processing method, and distribute the request to the corresponding method for processing. (Such as @RequestMapping, @GetMapping, @PostMapping, etc.)
Parameter binding Bind the parameters in the request to the parameters of the method to facilitate obtaining and processing request parameters. (Such as @RequestParam, @PathVariable, @RequestBody, etc.)
response handling Convert the method's return value into an HTTP response body and return it to the client. Data in JSON, XML and other formats can be easily returned. (Such as @ResponseBody, @RestController, etc.)
form processing Convert the method's return value into an HTTP response body and return it to the client. Data in JSON, XML and other formats can be easily returned. (Such as @ResponseBody, @RestController, etc.)
Exception handling Handle exceptions that occur in the application and return appropriate error messages or pages. (Such as @ExceptionHandler, @ControllerAdvice, etc.)
Session management Store and obtain data in the session to implement session management functions. (Such as @SessionAttribute, @SessionAttributes, etc.)
Configuration management Configure and manage various components and configuration items in the SpringMVC framework. (Such as @Configuration, @Bean, @ComponentScan, etc.)

Import slf4j related dependencies and configuration projects

First, replace the original log4j plug-in dependencies in the pom.xml file with the Slf4j plug-in dependencies, and replace all the original log4j core packages with the Slf4j core packages.

 pom.xml file

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.yx</groupId>
  <artifactId>yx_ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>yx_ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>

    <!--添加jar包依赖-->
    <!--1.spring 5.0.2.RELEASE相关-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!--2.mybatis相关-->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql-->
    <mysql.version>5.1.44</mysql.version>
    <!--pagehelper分页jar依赖-->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!--mybatis与spring集成jar依赖-->
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <!--3.dbcp2连接池相关 druid-->
    <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    <commons.pool2.version>2.4.3</commons.pool2.version>
    <!--4.log日志相关-->
    <!--  替换为slf4j日志相关 -->
    <log4j2.version>2.9.1</log4j2.version>
    <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
    <slf4j.version>1.7.13</slf4j.version>
    <!--5.其他-->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <lombok.version>1.18.2</lombok.version>

    <!-- jstl+standard -->
    <jstl.version>1.2</jstl.version>
    <standard.version>1.1.2</standard.version>
    <!-- spring -->
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>


  <dependencies>
    <!--1.spring相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--2.mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!--pagehelper分页插件jar包依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!--mybatis与spring集成jar包依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>

    <!--3.dbcp2连接池相关-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>${commons.dbcp2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>${commons.pool2.version}</version>
    </dependency>

    <!--4.log日志相关依赖-->
    <!--核心log4j2jar包-->
    <!--替换为 slf4j包   -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>

    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--用于与slf4j保持桥接-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
      <scope>runtime</scope>
    </dependency>

    <!--需要使用log4j2的AsyncLogger需要包含disruptor-->
    <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>${log4j2.disruptor.version}</version>
    </dependency>
    <!--5.其他-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

    <!-- spring mvc相关依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>${standard.version}</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>yx_ssm</finalName>
    <resources>
      <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>jdbc.properties</include>
          <include>*.xml</include>
        </includes>
      </resource>
    </resources>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>${maven.compiler.plugin.version}</version>
          <configuration>
            <source>${maven.compiler.source}</source>
            <target>${maven.compiler.target}</target>
            <encoding>${project.build.sourceEncoding}</encoding>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.2</version>
          <dependencies>
            <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
            <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>${mysql.version}</version>
            </dependency>
          </dependencies>
          <configuration>
            <overwrite>true</overwrite>
          </configuration>
        </plugin>

        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
  </build>
</project>

 

 

2. Parameter transfer

Configure running project

1. Basic type + String type

test code

package com.yx.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-05 15:22
 * 用于实现参数传递的控制器类
 */
@Slf4j
@Controller
@RequestMapping("/yx")
public class ParamController {
    
    @RequestMapping("/test01")//标记方法
    public String test01a(String bname,Integer bid){//参数
        log.info("简单类型参数:bname:{},bid:{}",bname,bid);
        return "index";//返回的页面
    }
    
}

Test Results

page

console

2. Complex types

test code
package com.yx.web;

import com.yx.model.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-05 15:22
 * 用于实现参数传递的控制器类
 */
@Slf4j
@Controller
@RequestMapping("/yx")
public class ParamController {

    @RequestMapping("/test02")//标记方法
    public String test02(Book book, HttpServletRequest request){//参数
        //        复杂传参输出方式01
        log.info("复杂类型参数:bname:{},bid:{},price{}",
                request.getParameter("bname"),
                request.getParameter("bid"),
                request.getParameter("price"));
//        复杂传参输出方式02
        log.info("复杂类型参数:book:{}",book.toString());
        return "index";//返回的页面
    }
}
Test Results
page

console

3. @RequestParam

test code
package com.yx.web;

import com.yx.model.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-05 15:22
 * 用于实现参数传递的控制器类
 */
@Slf4j
@Controller
@RequestMapping("/yx")
public class ParamController {

    @RequestMapping("/test03")//标记方法
    public String test03(
           @RequestParam String bname,
           @RequestParam(required = false) Integer bid){//参数
        log.info("@requestParam传参:bname:{},bid:{}",bname,bid);
        return "index";//返回的页面
    }
}
Test Results
Result one:

page

console output

Result two:

page

console

Result three:

page

console output

No results will be output.

Note: required attribute of @RequestParam

 Whether this parameter is required. The default is true , which means that the corresponding parameters must be passed in the request, otherwise a 404 error will be reported . If set to false, when there is no such parameter in the request, it will default to null. For variables of basic data types, it must If there is a value, a null pointer exception will be thrown . If null values ​​are allowed, variables in the interface need to be declared using a wrapper class.

4. @PathVariable

test code
package com.yx.web;

import com.yx.model.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-05 15:22
 * 用于实现参数传递的控制器类
 */
@Slf4j
@Controller
@RequestMapping("/yx")
public class ParamController {

    @RequestMapping("/test04/{bid}")//标记方法
    public String test04(
           @PathVariable("bid") Integer bid){//参数
        log.info("@PathVariable传参:bid:{}",bid);
        return "index";//返回的页面
    }

}
Test Results
page

 console output

 5.@RequestBody

Import @RequestBody dependency

 <jackson.version>2.9.3</jackson.version>
//======以上代码添加到pom.xml文件中的 <properties>标签中=======================
//======以下代码添加到pom.xml文件中的 <dependencies>标签中====================
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>
test code

Please use tools such as postman or apipost/eolink to send request data. Because the browser cannot carry collection parameters, third-party software is used for testing.

 

package com.yx.web;

import com.yx.model.Book;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-05 15:22
 * 用于实现参数传递的控制器类
 */
@Slf4j
@Controller
@RequestMapping("/yx")
public class ParamController {


    @RequestMapping("/test05")//标记方法
    public String test05(
           @RequestBody Map map){//参数
        log.info("@RequestBody传参:map:{}",map);
        return "index";//返回的页面
    }
}

 Third-party software testing operations

Console output

 6. @RequestHeader

test code
package com.yx.web;

        import com.yx.model.Book;
        import lombok.extern.slf4j.Slf4j;
        import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.*;

        import javax.servlet.http.HttpServletRequest;
        import java.util.Map;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-05 15:22
 * 用于实现参数传递的控制器类
 */
@Slf4j
@Controller
@RequestMapping("/yx")
public class ParamController {

    @RequestMapping("/test06")//标记方法
    public String test06(
            @RequestHeader("jwt") String jwt){//参数
        log.info("@RequestHeader传参:jwt:{}",jwt);
        return "index";//返回的页面
    }

}

Third-party testing operations

 Console output

 3. Method return value

Create a ReturnController class simulation test case

Case 1: void

With the help of tools
package com.yx.untils;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class ResponseUtil {

	public static void write(HttpServletResponse response,Object o)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
	
	public static void writeJson(HttpServletResponse response,Object o)throws Exception{
		ObjectMapper om = new ObjectMapper();
//		om.writeValueAsString(o)代表了json串
		write(response, om.writeValueAsString(o));
	}
}
Test code
package com.yx.web;

import com.yx.untils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-06 18:45
 * 测试类
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {

    @RequestMapping("/hello1")
    public void hello1(HttpServletResponse response){
        Map<String,Object> map=new HashMap<>();
        map.put("code",200);
        map.put("msg","成功添加...");
        try {
            ResponseUtil.writeJson(response,map);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
Test results (results displayed on the page)

Case 2: String

This return value type has been reflected in the previous parameter transfer.

Case 3: String+model

jsp file code
<%--
  Created by IntelliJ IDEA.
  User: 86158
  Date: 2023/9/5
  Time: 15:49
  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>Hello 君易--鑨</h1>
名称:${name}
地址:${address}
</body>
</html>
 test code
package com.yx.web;

import com.yx.untils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-06 18:45
 * 测试类
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {

    @RequestMapping("/hello2")
    public String hello2(Model model,
                       HttpServletRequest request){
          model.addAttribute("name","君易--鑨");
          request.setAttribute("address","长沙");
      return "index";
    }


}
Run test results

 Case 4: ModelAndView

test code
package com.yx.web;

import com.yx.untils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-06 18:45
 * 测试类
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {


    @RequestMapping("/hello3")
    public ModelAndView hello3(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("sign","真厉害");
        mv.setViewName("index");
        return mv;
    }
}
jsp file
<%--
  Created by IntelliJ IDEA.
  User: 86158
  Date: 2023/9/5
  Time: 15:49
  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>Hello 君易--鑨</h1>
名称:${name}
地址:${address}
评价:${sign}
</body>
</html>
Test Results

 4. Page jump

test code
package com.yx.web;

import com.yx.untils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 君易--鑨
 * @site www.yangxin.com
 * @company 木易
 * @create  2023-09-06 18:45
 * 测试类
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {


//    场景一
    @RequestMapping("/hello4")
    public String hello4(){
        System.out.println("hello4...");
        return "forward:hello2";
    }

//    场景二:
    @RequestMapping("/hello5")
    public String hello5(){
        System.out.println("hello5...");
        return "forward:/yx/test05";
    }
//    场景三:
    @RequestMapping("/hello6")
    public String hello6(){
        System.out.println("hello6...");
        return "redirect:hello2";
    }

    //    场景四:
    @RequestMapping("/hello7")
    public String hello7(){
        System.out.println("hello7...");
        return "redirect:/yx/test05";
    }

}

Scenario 1: (Forwarded to a certain method in the background (current class))

Test Results

Scenario 2: (Forwarded to a certain method in the background (other classes))

Test Results

​​​​​​​

Scenario 3: (Redirect to a certain method in the background (current class))

Test Results

Scenario 4: (Redirect to a certain method in the background (other classes))

Test Results

 

in conclusion

  • If the return value contains forward and redirect, the attempt parser will be bypassed.
  • Redirecting will change the request path, forwarding will not. ​​​​​​​

 This ends this sharing. Thank you all for your strong support.

​​​​​​​

Guess you like

Origin blog.csdn.net/weixin_74352229/article/details/132691265