SpringMVC common annotations, parameter transfer, return value

Table of contents

Preface

1. Commonly used annotations

2. Parameter transfer

Edit

1. Basic type + String type

2. Complex types

3. @RequestParam

4. @PathVariable

 5.@RequestBody

6. @RequestHeader

 3. Method return value

1: void

Two: String

Three: String+model

 Four: ModelAndView

 4. Page jump


Preface

In the previous blog, we had a preliminary understanding of the basic knowledge of SpringMVC. Let's continue to learn the common annotations, parameter transfer, and return values ​​of SpringMVC. I hope this blog can help you! ! !

1. Commonly used annotations

1. Common annotations for SpringMVC

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

2. RequestMapping : A 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.).

Marked on the method
is used on the method, indicating that appending the address in the annotation on the method under the parent path of the class will access the method.
 

@Controller
public class HelloController {

    @RequestMapping("/requestTest")
    public String requestTest(){
        return "index";
    }
}

Marked on classes and methods
. Used on classes, indicating that all methods in the class that respond to requests use this address as the parent path.

Note: When you add the RequestMapping annotation to a class, if you want to request mapping, it means that the request must first be mapped to the location of the annotated class, and then mapped to the method of the class.

@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/requestTest")
    public String requestTest(){
        return "index";
    }
}


 

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: Annotation can obtain the specified request header information.

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

Specific operations

1. Replace the original log4j plug-in dependency in the pom.xml file with the Slf4j plug-in dependency.

Replace the pom.xml file (replace all here to avoid copying errors)

<?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>

Test whether the plug-in is installed successfully

2. Parameter transfer

Configure running project

1. Basic type + String type

test code

package com.lya.web;

import com.lya.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.xiaolige.com
 * @company 猪八戒有限集团
 * @create 2023-09-05-15:50
 */
@Slf4j
@Controller
@RequestMapping("/param")
public class ParamController {

    @RequestMapping("/hello1")
    public String index(Integer bid ,String bname) {
    log.info("简单参数:bid:{},bname:{} ",bid,bname);
    return "index";
    }
}

2. Complex types

test code


    @RequestMapping("/hello2")
    public String hello2(Book book , HttpServletRequest httpServletRequest) {
        log.info("复杂参数:bid:{},bname:{} ",
                httpServletRequest.getParameter("bid"),
                httpServletRequest.getParameter("bname"));
        log.info("复杂参数:book:{} ",
                book.toString());
        return "index";
    }

3. @RequestParam

test code

    @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";
    }

console output

No results will be output.

Note: the 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

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

 5.@RequestBody

Import @RequestBody dependency

 <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>

test code

    @RequestMapping("/hello5")
    public String toHello5(@RequestBody Map map){
        System.out.println(map);
        return "index";
    }

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.

6. @RequestHeader

test code

@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";
    }

 3. Method return value

Create a ReturnController class simulation test case

1: void

With the help of tools

package com.lya.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();
		write(response, om.writeValueAsString(o));
	}
}

code

package com.lya.web;
 
import com.lya.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.xiaolige.com
 * @company 猪八戒有限集团
 * @create 2023-09-06-15:50
 */
@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();
        }
 
    }
 
}

Two: String

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

Three: String+model

<%--
  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.lya.web;
 
import com.lya.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.xiaolige.com
 * @company 猪八戒有限集团
 * @create 2023-09-06-16:50
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {
 
    @RequestMapping("/hello2")
    public String hello2(Model model,
                       HttpServletRequest request){
          model.addAttribute("name","刘彬彬");
          request.setAttribute("address","傻鸟");
      return "index";
    }
 
 
}

 Four: ModelAndView

test code

package com.lya.web;
 
import com.lya.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.xiaolige.com
 * @company 猪八戒有限集团
 * @create 2023-09-05-15:50
 * 测试类
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {
 
 
    @RequestMapping("/hello3")
    public ModelAndView hello3(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("sign","耗子没有摸鱼");
        mv.setViewName("index");
        return mv;
    }
}

 4. Page jump

The two jump methods of forward (forward: path) and redirect (redirect: path) will bypass the prefix and suffix of the view resolver ; also, if they are in the same controller, there is no need to use "/" from the root directory Start, and if it is in a different controller, it must start from the root directory.

path is the request processing method name, not the logical view name.

  • Forward (the address bar remains unchanged)

@RequestMapping("/helloPage1")
    public String toHelloPage1(){
        System.out.println("helloPage1");
        return "forward:toHello2";
    }

It is equivalent to "request.getRequestDispatcher("url").forward(request,response)". Using forwarding, you can forward it to jsp or other controller methods.

  • Redirect (address bar changes)

@RequestMapping("/helloPage2")
    public String toHelloPage2(){
        System.out.println("helloPage2");
        return "redirect:toHello2";
    }

It is equivalent to "response.sendRedirect(url)". It should be noted that if you redirect to a jsp page, the jsp page cannot be written in the WEB-INF directory, otherwise it cannot be found.

Jump to other controllers

@RequestMapping("/helloPage3")
    public String toHelloPage3(){
        System.out.println("helloPage3");
        return "forward:/demo/hello";
    }
    @RequestMapping("/helloPage4")
    public String toHelloPage4(){
        System.out.println("helloPage4");
        return "redirect:/demo/hello";
    }

Guess you like

Origin blog.csdn.net/m0_73647713/article/details/132724025