SpringMVC中的综合案例

news2025/4/13 1:25:56

目录

一.常用注解

 实例:

 二.参数转递

 2.1. 基础类型

2.2. 复杂类型

2.3. @RequestParam

2.4.@PathVariable

2.5.@RequestBody

 2.6.RequestHeader 

2.7. 请求方法

三.返回值

3.1.void

 3.2.String

3.3 String+Model

3.4 ModelAndView

四、页面跳转

 4.1.转发

4.2.重定向

最后SpringMVC综合案例就到这里,祝大家在敲代码的路上一路通畅!

感谢大家的观看 !


一.常用注解

  • @RequestMapping:@RequestMapping注解是一个用来处理请求地址映射的注解,可用于映射一个请求或一个方法,可以用在类或方法上。
  • @RequestParam:@RequestParam主要用于将请求参数区域的数据映射到控制层方法的参数上

  • @ModelAttribute:

  1. 绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;

  2. 暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;

  3. 暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。

  • @SessionAttributes:用于将数据存储到会话(Session)中,在多个请求之间共享数据。

  • @RequestBody:用于将方法的返回值直接作为响应体返回给客户端,常用于返回JSON数据。

  • @RequestHeader:使用 @RequestHeader 注解可以获取指定的请求头信息。

  • @PathVariable:该注解请求URI中的模板变量部分到处理器功能处理方法的方法参数上的绑定。

  • @CookieValue:@CookieValue注解主要是将请求的Cookie数据,映射到功能处理方法的参数上。

 实例:

@RequestMapping:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, params = "active=true")
    public String getActiveUser(@PathVariable("id") int id) {
        // ...
    }
}

@RequestParam:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createUser(@RequestParam("user") User user) {
        // ...
    }
}

@ModelAttribute:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createUser(@ModelAttribute("user") @Valid User user, BindingResult result) {
        // ...
    }
}

@SessionAttributes:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editUser(@ModelAttribute("user") User user) {
        // ...
    }
}

@RequestBody:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createUser(@RequestBody @Valid User user, BindingResult result) {
        // ...
    }
}

@RequestHeader:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public String updateUserInfo(@RequestHeader("Content-Type") String contentType, 
                                 @RequestHeader("Authorization") String authorization) {
        // ...
    }
}

@PathVariable:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/{id}/info/{name}", method = RequestMethod.GET)
    public String getUserInfo(@PathVariable("id") int userId, 
                              @PathVariable("name") String userName) {
        // ...
    }
}

@CookieValue:

@Controller
@RequestMapping("/users")
public class UserController {
    
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String getUserInfo(@CookieValue("sessionId") String sessionId, 
                              @CookieValue("userId") int userId) {
        // ...
    }
}

 二.参数转递

配置项目中的 pom.xml 配置文件 ,以下配置(修改)完后的所有配置:

<?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>org.example</groupId>
  <artifactId>index</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
 
  <name>index 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日志相关-->
    <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>
    <jackson.version>2.9.3</jackson.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>
 
    <!-- log4j2日志相关依赖 -->
    <!-- log配置:Log4j2 + Slf4j -->
    <!-- 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>
 
    <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>
 
    <!--核心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>
 
    <!-- 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>index</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.1. 基础类型

@RequestMapping("/hello1")
    public String toHello1(Integer bid,String bname){
        log.info(">>>> 基础类型+String传参:{},{}",bid,bname);
        return "index";
    }

 新建一个paramController类:

package com.junlinyi.web;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
/**
 * @author 君临沂
 * @site www.junlinyi.com
 * @company 君氏集团
 * @create 2023-09-05-14:44
 */
@Slf4j
@Controller
@RequestMapping("/param")
public class ParamController {
    @RequestMapping("/hello1")
    public String index(String bname,Integer bid){
//        System.out.println("刘三金去拿奶茶喽。。。");
        log.info("简单类型参数:bname:{},bid:{}",bname,bid);
        return "index";
    }
}

  index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>看你不爽哦</h1>
</body>
</html>

效果显示:

 

2.2. 复杂类型

@RequestMapping("/hello2")
    public String toHello2(Book book,
                           HttpServletRequest req,
                           HttpServletResponse resp,
                           HttpSession session){
        System.out.println(book);
        log.info(">>>> HttpServletRequest/HttpServletResponse/HttpSession等等传参:{}", req.getRequestURI());
        return "index";
    } 

在paramController类中添加以下方法:

@RequestMapping("/hello2")
    public String hello2(Book book, HttpServletRequest request){
//        System.out.println("靓仔来了喽。。。");
        //servlet参数获取方式
        log.info("复杂类型参数:bname:{},bid:{}",
                request.getParameter("bname"),
                request.getParameter("bid"));
        //复杂传参
        log.info("复杂类型参数:book:{}",
                book.toString());
//      fail..error warning info debug
        return "index";
    }

效果演示:

2.3. @RequestParam

@RequestMapping("/hello3")
    public String toHello3(@RequestParam Integer bid,
                           @RequestParam(required = false,value = "price") Integer bookPrice,
                           @RequestParam("bookName") String bname){
        log.info(">>>> 使用@RequestParam注解传递参数:{},{},{}", bid,bname,bookPrice);
        return "index";
    }

在paramController类中添加以下方法:

@RequestMapping("/hello3")
        public String hello3(
               @RequestParam String bname,
               @RequestParam(required = false) Integer bid){
//        System.out.println("靓仔来了喽。。。");
            log.info("@requestParam参数:bname:{},bid:{}",bname,bid);
//      fail..error warning info debug
            return "index";
        }

 注意:

演示效果:

根据条件输入 正确地址:

 

 

2.4.@PathVariable

@RequestMapping("/hello4/{bid}")
    public String toHello4(@PathVariable("bid") Integer bid){
        log.info(">>>> 使用@PathVariable注解传递参数:{}", bid);
        return "index";
    }

在paramController类中添加以下方法:

@RequestMapping("/hello4/{bid}")
    public String hello4(@PathVariable("bid") Integer bid){
//        System.out.println("靓仔来了喽。。。");
        log.info("@requestParam参数:bid:{}",bid);
//      fail..error warning info debug
        return "index";
    }

 演示效果:

 

2.5.@RequestBody

在进行@RequestBody传参前先要在pom.xml传入依赖,如下:

<jackson.version>2.9.3</jackson.version>
 
 <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>

这里我们需要在Eolink Apikit软件工具上进行测试请求地址:

按照以下步骤把参数填写好,query参数是往域名链接添加属性,如下:

然后介绍完Query参数后就开始添加我们的请求体参数,如下:

 2.6.RequestHeader 

@RequestMapping("/hello7")
    public String toHello7(Book book, @RequestBody Map map, @RequestHeader("jwt") String jwt){
        System.out.println(map);
        System.out.println(book);
        System.out.println(jwt);
        return "index";
    }

方法代码如下:

 @RequestMapping("/hello7")
    public String hello7(@RequestHeader("jwt") String jwt){
//        System.out.println("靓仔来了喽。。。");
        log.info("@RequestHeader参数:jwt:{}",jwt);
//      fail..error warning info debug
        return "index";
    }
 
    @RequestMapping("/hello8")
    public String hello8(Book book,
            @RequestBody Map map,
            @RequestHeader("jwt") String jwt){
//        System.out.println(""靓仔来了喽。。。");
        log.info("Book:Book:{}",book.toString());
        log.info("@RequestBody参数:Map:{}",map);
        log.info("@RequestHeader参数:jwt:{}",jwt);
//      fail..error warning info debug
        return "index";
    }

代码完成之后我们需要在Eolink中进行头部请求参数配置,如下: 

然后进行测试结果如下:

最后我们再来测试以下方法八,个人配置如下:

 

2.7. 请求方法

请求方法有:

RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping

他们之间的关系为:

RequestMapping=GetMapping+PostMapping+PutMapping+DeleteMapping

RequestMapping与GetMapping、PostMapping、PutMapping、DeleteMapping的区别

RequestMapping不安全,且不具备标识意义。

测试方法如下:

//查询的请求
    @GetMapping
    public String type1(){
        System.out.println("@GetMapping:对应查询请求");
        return "index";
    }
 
    //新增的请求
    @PostMapping
    public String type2(){
        System.out.println("@PostMapping:对应新增请求");
        return "index";
    }
 
    //修改的请求
    @PutMapping
    public String type3(){
        System.out.println("@PutMapping:对应修改请求");
        return "index";
    }
 
    //删除的请求
    @DeleteMapping
    public String type4(){
        System.out.println("@DeleteMapping:对应删除请求");
        return "index";
    }
 
    //RequestMapping=GetMapping+PostMapping+PutMapping+DeleteMapping
    //RequestMapping不安全,且不具备标识意义

依次进行请求,请求的方式不同会进行不同的请求注解,具体操作与效果如下:

三.返回值

创建一个ResponseUtil工具类,辅助完成测试代码,如下

package com.junlinyi.utils;
 
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));
	}
}

创建一个ReturnController类,来进行方法的请求测试(包含关于返回值的所以方法)。如下: 

package com.junlinyi.web;
 
import com.junlinyi.utils.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
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.junlinyi.com
 * @company 君氏集团
 * @create 2023-09-05-14:44
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {
 
    @RequestMapping("/test01")
    public void Test01(HttpServletResponse response) throws Exception {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",1);
        map.put("晚安","亲爱的梦");
        map.put("梦","增加成功!!!");
        ResponseUtil.writeJson(response,map);
    }
 
    @ResponseBody
    @RequestMapping("/test02")
    public Map Test02(HttpServletResponse response) throws Exception {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",1);
        map.put("晚安","亲爱的梦");
        map.put("梦","增加成功!!!");
        return map;
    }
 
    @RequestMapping("/test03")
    public String Test03() {
        return "index02";
    }
 
    @RequestMapping("/test04")
    public String Test04(
            Model model,
            HttpServletRequest request) {
        model.addAttribute("Nobo1","他字字句句喜欢你");
        request.setAttribute("Nobo1","我曾经也想过一了百了");
        return "index02";
    }
 
    @RequestMapping("/test05")
    public ModelAndView Test05() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("Nobo2","他字字句句喜欢你");
        modelAndView.addObject("Nobo2","我曾经也想过一了百了");
        modelAndView.setViewName("index02");
        return modelAndView;
    }
 
}

创建一个index.jsp页面进行显示测试,如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>字字句句喜欢你</h1>
歌词上句:  ${Nobo1}<br>
歌词下句:  ${Nobo2}
</body>
</html>

3.1.void

处理器对请求处理后,无需跳转到其它任何资源,此时可以让处理器方法返回 void。

 3.2.String

3.3 String+Model

打开浏览器输入相对应地址,结果如下:

Model测试:

将test03换成test04接着输出即可:

3.4 ModelAndView

打开浏览器输入相应请求地址,结果如下:

四、页面跳转

创建一个PathConterller测试类,进行页面跳转的各种方法测试,代码如下: 

package com.junlinyi.web;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author 君临沂
 * @site www.junlinyi.com
 * @company 君氏集团
 * @create 2023-09-06-16:19
 */@Controller
@RequestMapping("/ts")
public class PathConterller {
 
    @ResponseBody
    @RequestMapping("/test02")
    public Map Test02(HttpServletResponse response) throws Exception {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",1);
        map.put("晚安","亲爱的梦");
        map.put("梦","增加成功!!!");
        return map;
    }
 
    //返回值中有转发(forward)和重定向(redirect)这两种跳转方式将会绕开视图解析器的前缀和后缀
 
    //转发到(当前类)的某一个方法
    @RequestMapping("/Demo01")
    public String Demo01(){
        System.out.println("请求地址:Demo01");
        System.out.println("转发到(当前类)的某一个方法");
        return "forward:test02";
    }
 
    //转发到(其他类)的某一个方法
    @RequestMapping("/Demo02")
    public String Demo02(){
        System.out.println("请求地址:Demo02");
        System.out.println("转发到(其他类)的某一个方法");
        return "forward:/rs/test04";
    }
 
    //重定向到(其他类)的某一个方法
    @RequestMapping("/Demo03")
    public String Demo03(){
        System.out.println("请求地址:Demo03");
        System.out.println("重定向到(其他类)的某一个方法");
        return "redirect:test02";
    }
 
    //重定向到(其他类)的某一个方法
    @RequestMapping("/Demo04")
    public String Demo04(){
        System.out.println("请求地址:Demo04");
        System.out.println("重定向到(其他类)的某一个方法");
        return "redirect:/rs/test04";
    }
 
 
}

 4.1.转发

它相当于“request.getRequestDispatcher("url").forward(request,response)”。使用转发,既可以转发到jsp, 也可以转发到其他的控制器方法。

 打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo02,结果如下:

4.2.重定向

打开服务器 ,在浏览器上方输入对应请求地址此处输入Demo04,结果如下:

最后SpringMVC综合案例就到这里,祝大家在敲代码的路上一路通畅!

感谢大家的观看 !

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/980833.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

zk羊群效应怎么处理

什么是zk的羊群效应 如下图&#xff0c;如果第一个锁挂了&#xff0c;其他客户端又全监听的它&#xff0c;如果几十上百个&#xff0c;之个锁挂了还得去一个个通知&#xff0c;我挂了&#xff0c;你们又要重新加锁&#xff0c;全又监听。会引起多余的请求与网络开销。 如果这个…

虚拟机的ubuntu 22.04无法联网问题解决

问题&#xff1a;虚拟机的ubuntu 22.04无法联网 解决&#xff1a; 找到一种配置的方式&#xff0c;使用命令&#xff1a;sudo dhclient -v

MIT的智慧,利用深度学习来解决了交通堵塞

导读大家都对交通阻塞深恶痛绝。除了让人头疼和错过约会之外&#xff0c;交通拥堵让美国的司机每年多花3000亿美元。 研究人员建议大家使用自动驾驶汽车&#xff0c;即使数量占比并不大&#xff0c;但也能大大改善交通拥堵情况。 Lex Fridman和他的MIT团队开发了一款模拟游戏来…

SpringBoot环境MongoDB分页+去重+获取去重后的原始数据

最近有个比较复杂的MongoDB查询需求&#xff0c; 要求1&#xff1a;获取最近订单表中的请求参数信息&#xff0c;并需要按照请求参数中的账号进行去重 要求2&#xff1a;数据量可能比较大&#xff0c;因此需要做分页查询 研究了大半天&#xff0c;终于搞出了解决方案&#xff0…

使用 Python 的高效相机流

一、说明 让我们谈谈在Python中使用网络摄像头。我有一个简单的任务&#xff0c;从相机读取帧&#xff0c;并在每一帧上运行神经网络。对于一个特定的网络摄像头&#xff0c;我在设置目标 fps 时遇到了问题&#xff08;正如我现在所理解的——因为相机可以用 mjpeg 格式运行 30…

手写Spring:第6章-资源加载器解析文件注册对象

文章目录 一、目标&#xff1a;资源加载器解析文件注册对象二、设计&#xff1a;资源加载器解析文件注册对象三、实现&#xff1a;资源加载器解析文件注册对象3.1 工程结构3.2 资源加载器解析文件注册对象类图3.3 类工具类3.4 资源加载接口定义和实现3.4.1 定义资源加载接口3.4…

面试算法-常用数据结构

文章目录 数据结构数组链表 栈队列双端队列树 1&#xff09;算法和数据结构 2&#xff09;判断候选人的标准 算法能力能够准确辨别一个程序员的功底是否扎实 数据结构 数组 链表 优点&#xff1a; 1&#xff09;O(1)时间删除或者添加 灵活分配内存空间 缺点&#xff1a; 2&…

把文件上传到Gitee的详细步骤

目录 第一步&#xff1a;创建一个空仓库 第二步&#xff1a;找到你想上传的文件所在的地址&#xff0c;打开命令窗口&#xff0c;git init 第三步&#xff1a;git add 想上传的文件 &#xff0c;git commit -m "给这次提交取个名字" 第四步&#xff1a;和咱们在第…

生成多样、真实的评论(2019 IEEE International Conference on Big Data )

论文题目&#xff08;Title&#xff09;&#xff1a;Learning to Generate Diverse and Authentic Reviews via an Encoder-Decoder Model with Transformer and GRU 研究问题&#xff08;Question&#xff09;&#xff1a;评论生成&#xff0c;由上下文评论->生成评论 研…

Android之“写死”数据

何为“写死”&#xff0c;即写完之后除非手动修改&#xff0c;否像嘎了一样在那固定死了 在实际安卓开发中&#xff0c;这种写死的概念必不可少&#xff0c;如控件的id&#xff0c;某一常量&#xff0c;Kotlin中的Val 当然&#xff0c;有些需求可能也会要求我们去写死数据&am…

实战:大数据Flink CDC同步Mysql数据到ElasticSearch

文章目录 前言知识积累CDC简介CDC的种类常见的CDC方案比较 Springboot接入Flink CDC环境准备项目搭建 本地运行集群运行将项目打包将包传入集群启动远程将包部署到flink集群 写在最后 前言 前面的博文我们分享了大数据分布式流处理计算框架Flink和其基础环境的搭建&#xff0c…

入门力扣自学笔记279 C++ (题目编号:1123)

1123. 最深叶节点的最近公共祖先 题目&#xff1a; 给你一个有根节点 root 的二叉树&#xff0c;返回它 最深的叶节点的最近公共祖先 。 回想一下&#xff1a; 叶节点 是二叉树中没有子节点的节点树的根节点的 深度 为 0&#xff0c;如果某一节点的深度为 d&#xff0c;那它…

PyCharm中使用matplotlib.pyplot.show()报错MatplotlibDeprecationWarning的解决方案

其实这只是一个警告&#xff0c;忽略也可。 一、控制台输出 MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later. MatplotlibD…

iOS 17中的Safari配置文件改变了游戏规则,那么如何设置呢

Safari在iOS 17中最大的升级是浏览配置文件——能够在一个应用程序中创建单独的选项卡和书签组。这些也可以跟随你的iPad和Mac&#xff0c;但在本指南中&#xff0c;我们将向你展示如何使用运行iOS 17的iPhone。 你可能有点困惑&#xff0c;为什么Safari中没有明显的位置可以添…

Power BI的发布到web按钮怎么没有?有人知道怎么办吗??????

Power BI的发布到web按钮怎么没有&#xff1f;有人知道怎么办吗&#xff1f;&#xff1f;&#xff1f;&#xff1f;&#xff1f; .

使用Spring-data-jpa

EnableJpaAuditing 它是用来启动Jpa的审计功能。 jpa querydsl 多表的联合查询 导入依赖 querydsl-jpa 、querydsl-apt Repository接口, 继承QuerydslPredicateExecutor接口 NoRepositoryBean public interface BaseMongoRepository<T> extends MongoRepository<T…

GptFuck—开源Gpt4分享

这个项目不错&#xff0c;分享给大家 项目地址传送门

c语言 2.0

1.数据类型 数据类型介绍 数据类型&#xff1a;c语言中数据类型有3种&#xff0c;分别是基本数据类型、构造数据类型、指针数据类型。 数据类型的作用&#xff1a;编译器预算数据分配的内存空间大小。 ps&#xff1a;可以通俗理解为&#xff1a;数据类型是用来规范内存的开销…

避坑之路 —— 前后端 json 的注意问题

当我们在进行开发项目的时候&#xff0c;在前后端需要进行数据之间的传输&#xff0c;那么就会需要到json。而json算是字符串中的一种 1.先说一下前端的, 其实这两种都是表示前端希望能收到后端json这样的数据格式&#xff0c;那么我们在后端就需要注意将数据进行转换为json进…

Python实现猎人猎物优化算法(HPO)优化卷积神经网络回归模型(CNN回归算法)项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档视频讲解&#xff09;&#xff0c;如需数据代码文档视频讲解可以直接到文章最后获取。 1.项目背景 猎人猎物优化搜索算法(Hunter–prey optimizer, HPO)是由Naruei& Keynia于2022年提出的一种最新的…