[SpringMVC] Parameter Passing with User Requests and Responses

Time:2023-10-4

catalogs

I. Postman Tool Usage

1.1 Postman Installation

1.2 Use of Postman

1.2.1 Creating WorkSpace workspaces

1.2.2 Creating requests

 

II. Parameter passing

2.1 Adding Slf4j dependencies

2.2 General parameter passing

Knowledge 1: @RequestMapping

Knowledge Point 2: @RequestParam

2.3 Path Passing Parameters

Knowledge Point 3: @PathVariable

2.4 Json Data Passing

Knowledge Point 4: @RequestBody

 

III. Response

3.1 Responding to Json Data

3.2 Jump page response data

3.3 ModelAndView Response

 

IV. Page jumps

4.1 Forwarding (address bar unchanged)

4.2 Redirection (address bar change)

4.3 Jumping other controllers

One,Postman Tool Use

Before that learn about Postman tool, Postman is a popular API development and testing tool that provides a user-friendly interface for sending HTTP requests and viewing responses. It helps developers to be more efficient and convenient in developing and testing APIs.

We need frequent data testing when writing web programs , sent GET requests can be used directly using the browser , if the request is sent to the post request , we have to prepare the page on the page to prepare the form form , testing is more troublesome . So we need to use some third-party tools, such as Postman, Eolink …

1.1 Postman Installation

Postman official download addresshttps://www.postman.com/downloads/

[SpringMVC] Parameter Passing with User Requests and Responses

Double-click the automatic installation, the first time we need to register into the login can also choose to skip, such as the need to test also have to login a hand. You can point can follow the prompts to register, the following interface is the main interface after I login.

[SpringMVC] Parameter Passing with User Requests and Responses

1.2 Use of Postman

1.2.1 Creating WorkSpace workspaces

Create a new workspace and set the workspace name:

[SpringMVC] Parameter Passing with User Requests and Responses

1.2.2 Creating requests

Select the workspace you just created and add a request:

[SpringMVC] Parameter Passing with User Requests and Responses

[SpringMVC] Parameter Passing with User Requests and Responses

Caution: The You need to create a new directory for the first request, and then you don’t need to create a new directory, you can just save to the already created directory.

II. Parameter passing

Previous We’re done.Introductory caseRelated knowledge learning, we know that SpringMVC is the web layer of the framework, the main role is to receive requests, receive data, respond to the results, so this chapter is the focus of learning SpringMVC content.

2.1 Adding Slf4j dependencies

<log4j2.version>2.9.1</log4j2.version>
<log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
<slf4j.version>1.7.13</slf4j.version>

<! --4.log log related dependencies -->

<! -- log4j2 logging related dependencies -->
<! -- log configuration: Log4j2 + Slf4j -->
<! -- slf4j core package -->
<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>

<! ---core log4j2jar package -->
<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>
<! --- Used to maintain a bridge with slf4j -->
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-slf4j-impl</artifactId>
	<version>${log4j2.version}</version>
</dependency>
<! --web projects need to include log4j-web, non-web projects do not -->
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-web</artifactId>
	<version>${log4j2.version}</version>
	<scope>runtime</scope>
</dependency>

<! --- AsyncLogger that requires log4j2 needs to include disruptor -->
<dependency>
	<groupId>com.lmax</groupId>
	<artifactId>disruptor</artifactId>
	<version>${log4j2.disruptor.version}</version>
</dependency>

In the previous article in the pom.xml configuration file to replace the log4j dependency, in the actual development of the log file will usually be used to save the data information. AndSlf4j(Simple Logging Facade for Java) is a simple Java logging facade framework , it provides a common logging interface , enabling developers to use different logging implementations in the application , without the need to modify the code.Slf4j’s goal is to provide a simple , flexible and scalable logging solution for Java applications .

2.2 General parameter passing

Write the paramController class

package com.ycxw.web;

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

/**
 * @author Yunmura Xiaowei
 * @site blog.csdn.net/Justw320
 * @create 2023-09-05 16:34
 */
@Slf4j
@Controller
@RequestMapping("/param")
public class ParamController {
    
    @RequestMapping("/hello1")
    public String toHello1(Integer bid,String bname){
        log.info("Base type + String passed parameter: bid {}",bid,bname);
        return "index";
    }
}

Knowledge 1: @RequestMapping

The @RequestMapping annotation is an annotation used to handle request address mapping, which can be used to map a request or a method, and can be used on classes or methods.

  • The @Slf4j annotation indicates that the class uses the Slf4j logging framework for logging.
  • The @Controller annotation indicates that this is a controller class for handling HTTP requests. The request mapping path for this class is “/param”.
  • In this class, a controller class named ParamController is defined. It contains a method named toHello1 that uses the @RequestMapping annotation to specify the URL path to process as “/hello1”. The method accepts two parameters, an integer bid of basic type and bname of string type.
  • Within the method body, a log message is recorded using the log.info method. This log message contains the values of two parameters, bid and bname, using {} placeholders to indicate the position of the parameters.
  • Finally, the method returns a string “index”, which is the name of the view to be rendered.

 

  • Ordinary parameter: url address pass parameter, address parameter name and formal parameter variable name is the same, define the formal parameter can receive parameter.

[SpringMVC] Parameter Passing with User Requests and Responses

Print results:

[SpringMVC] Parameter Passing with User Requests and Responses

Caution:Receiving data fails if the form participant address parameter names do not match.

[SpringMVC] Parameter Passing with User Requests and Responses

[SpringMVC] Parameter Passing with User Requests and Responses

Solution.utilization@RequestParamexplanatory note

 

Knowledge Point 2:@RequestParam

@RequestParam is mainly used to map data from the request parameter area to parameters of control layer methods

parametersclarification
valueThe name of the incoming parameter in the request, which will default to this variable name if the value value of the backend interface is not set.
requiredWhether this parameter is mandatory.The default is true, indicating that the corresponding parameter must be passed in the request.Otherwise, a 404 error will be reportedIf set to false, when the request does not contain this parameter, thewill default to null, whereas for basic data type variables, they must have a value, which will throw a null pointer exception.. If null values are allowed, variables in the interface need to be declared using a wrapper class.
defaultValueThe default value of the parameter, if there is no parameter with the same name in the request, the variable defaults to this value. Note that the default value can use a SpEL expression such as “#{systemProperties[‘java.vm.version’]}”
@RequestMapping("/hello2")
    public String toHello2(@RequestParam(required = false) Integer bid,
                           @RequestParam(value = "bhahaha") String bname) {
        log.info("Base type + String passed parameter: bid {}", bid, bname);
        return "index";
    }

At this point, using the @RequestParam annotation to set the foreground pass parameter name, you can use bhahaha to pass the value successfully.

[SpringMVC] Parameter Passing with User Requests and Responses

[SpringMVC] Parameter Passing with User Requests and Responses

2.3 Path Passing Parameters

Knowledge Point 3: @PathVariable

If I want to delete an item by id I can annotate it with PathVariable, example:

@RequestMapping("/hello3/{bid}")
    public String toHello3(@PathVariable("bid") Integer bid) {
        log.info("Passing parameters using @PathVariable annotation: {}", bid);
        return "index";
    }

Run results:[SpringMVC] Parameter Passing with User Requests and Responses

[SpringMVC] Parameter Passing with User Requests and Responses

2.4 Json Data Passing

In the actual development of the most widely used is the transfer of data through Json, in this article, we do not demonstrate the object, array, and the collection of transmission, the transmission method is slightly different from the ordinary parameter transfer.

SpringMVC uses jackson by default to handle json conversion, so you need to add the jackson dependency in 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>

 

Knowledge Point 4: @RequestBody

        @RequestBody An annotation is used to bind the contents of the request body of an HTTP request to the parameters of a method. It tells the Spring MVC framework to convert the content of the request body to the specified parameter type and pass it to the method for processing.

Parameters using the @RequestBody annotation can be of any Java object type, including custom POJO (Plain Old Java Object) classes.Spring MVC automatically converts the content of the request body to the specified parameter type using the appropriate converter based on the content type of the request body.

  • json object ({key1 value2,…})

Requests and data sent.

{
    "bid": 1,
    "bname": "doujinshi".
    "price": 9.9
}

[SpringMVC] Parameter Passing with User Requests and Responses 

The back-end receives the data:

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

[SpringMVC] Parameter Passing with User Requests and Responses 

 

  • array of json objects ([{key1 value2,…}])

Requests and data sent.

[{
    "bid": 1,
    "bname": "doujinshi".
    "price": 9.9
},
{
    "bid": 2,
    "bname": "doujinshi".
    "price": 10.9
}
]

[SpringMVC] Parameter Passing with User Requests and Responses

 

The back-end receives the data:

    @RequestMapping("/hello6")
    @ResponseBody
    public String toHello6(@RequestBody List<Book> books) {
        System.out.println(books);
        return "index";
    }

[SpringMVC] Parameter Passing with User Requests and Responses

 

@RequestBody is different from @RequestParam

Distinction:

  • @RequestParam is used to receive url address pass parameter, form pass parameter [application/x-www-form-urlencoded].
  • @RequestBody is used to receive json data [application/json].

Applications:

  • Later development, send json format data is the main, @RequestBody is more widely used
  • If you are sending non-json data, use @RequestParam to receive request parameters.

III. Response

3.1 Responding to Json Data

1. Creating the controller: ReturnController class

package com.ycxw.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Yunmura Xiaowei
 * @site blog.csdn.net/Justw320
 * @create 2023-09-06 22:18
 */
@Controller
@RequestMapping("/rs")
public class ReturnController {

}

2. Preparation of response data

@ResponseBody //Response Json Data
    @RequestMapping("/return1")
    public Map<String, Object> return1(HttpServletResponse response){
        Map<String,Object> maps = new HashMap<>();
        maps.put("code",200);
        maps.put("msg", "Response Successful");;
        return maps;
    }

3. Testing.

[SpringMVC] Parameter Passing with User Requests and Responses

3.2 Jump page response data

1. Prepare responsive jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
Nickname: ${name}
Love and hate: ${hobby}
</body>
</html>

2. Preparation of response data

@RequestMapping("/return2")
    public String return2(Model model, HttpServletRequest request){
        //Populate model data
        addAttribute("name"," Yuncun Xiaowei ");
        request.setAttribute("hobby"," programming ");
        //Logical view name
        return "index";
    }

3. Testing:

[SpringMVC] Parameter Passing with User Requests and Responses

3.3 ModelAndView Response

  1. ModelAndView is a class used in the Java Spring Framework to pass data model and view information together to the front-end page. It is a way of combining data and views together in a way that makes it easy for developers to process data in the back-end controller and pass it to the front-end page for presentation.
  2. In ModelAndView, “Model” denotes a data model, which is an object that stores data that can be set up in the back-end controller and passed to the front-end page. Developers can store data in the model using key-value pairs and then use this data in the front-end page for display or processing.
  3. View” represents the view, which is the representation of the front-end page. In ModelAndView, developers can set the name or path of the view to be displayed, so that after the request is processed, the data model will be passed to the corresponding view for rendering and display.
  4. By using ModelAndView, developers can encapsulate data and view information together and conveniently pass it to the front-end page to realize dynamic display and interaction of data. This approach makes the data transfer between the back-end controller and the front-end page more flexible and convenient.
@RequestMapping("/return3")
    public ModelAndView return3(){
        ModelAndView mv = new ModelAndView();
        //Populate model data
        mv.addObject("name", "cloud village Xiaowei");;
        mv.addObject("hobby", "programming");;
        //Logical view name
        mv.setViewName("index");
       
        return mv;
    }

Testing:

[SpringMVC] Parameter Passing with User Requests and Responses

IV. Page jumps

The two forward paths will bebypassThe view parser’sprefix (linguistics)andsuffix (linguistics)Also, you don’t need to use “/” to start from the root directory if you are in the same controller, but you must start from the root directory if you are in different controllers.

4.1 Forwarding (address bar unchanged)

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

[SpringMVC] Parameter Passing with User Requests and Responses

It is equivalent to “request.getRequestDispatcher(“url”).forward(request,response)”. With forwarding, you can either forward to jsp or to other controller methods.

4.2 Redirection (address bar change)

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

[SpringMVC] Parameter Passing with User Requests and Responses

It is equivalent to “response.sendRedirect(url)”, and can also be forwarded to other controller methods.

4.3 Jumping other controllers

/* Forwarding */
    @RequestMapping("/helloPage3")
    public String toHelloPage3(){
        System.out.println("helloPage3...");
        return "forward:/param/hello1";
    }
    
    /* Redirection */
    @RequestMapping("/helloPage4")
    public String toHelloPage4(){
        System.out.println("helloPage4...");
        return "redirect:/param/hello1";
    }

Test redirect: redirect:/param/hello1

[SpringMVC] Parameter Passing with User Requests and Responses

If it is in the same controller then you don’t need to use “/” to start from the root directory, but if it is in different controllers then you must start from the root directory.

Recommended Today

uniapp and applet set tabBar and show and hide tabBar

(1) Set the tabBar: uni.setTabberItem({}); wx.setTabberItem({}); indexnumberisWhich item of the tabBar, counting from the left, is indexed from 0.textstringnoButton text on tabiconPathstringnoImage PathselectedIconPathstringnoImage path when selectedpagePathstringnoPage absolute pathvisiblebooleannotab Whether to display uni.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) wx.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) […]