【WEEK2】 【DAY5】Data Processing and Redirection - Data Processing【English Version】

2024.3.8 Friday

Following the previous article 【WEEK2】 【DAY4】Data Processing and Redirection - Methods of Result Redirection 【English Version】

5.2. Data Processing

5.2.1. Submitting Processed Data

5.2.1.1. The submitted field name matches the parameter name of the processing method

Assuming the submitted data is: http://localhost:8080/hello?name=zhangsan
Processing method:

@RequestMapping("/hello")
public String hello(String name){
   System.out.println(name);
   return "hello";
}

Backend output: zhangsan

5.2.1.2. The submitted field name does not match the parameter name of the processing method

Assuming the submitted data is: http://localhost:8080/hello?username=zhangsan
Processing method:

//@RequestParam("username") : The name of the submitted field 'username'.
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
   System.out.println(name);
   return "hello";
}

Backend output: zhangsan

5.2.1.3. Example: Creating a New File

Insert image description here

1. UserController.java
package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
//    localhost:8080/user/t1?name=...
    @GetMapping("/t1")
    public String test1(String name, Model model){
        //1. Receive front-end parameters (via name)
        System.out.println("Front-end parameter received: " + name);
        
        //2. Pass the result back to the front-end: Model
        model.addAttribute("msg", name);

        //3. View transition
        return "test";
    }
}
2. Execution

http://localhost:8080/springmvc_04_controller_war_exploded/user/t1
Insert image description here
http://localhost:8080/springmvc_04_controller_war_exploded/user/t1?name=zhangsan
Insert image description here
Insert image description here

3. Modify UserController.java

(add @RequestParam(“username”))

package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/user")
public class UserController {
//    localhost:8080/user/t1?name=...
    @GetMapping("/t1")
    // It is common to write @RequestParam("username") for frontend reception, then the URL changes to localhost:8080/username/t1?name=...
    public String test1(@RequestParam("username") String name, Model model){
        //1. Receive front-end parameters (via name)
        System.out.println("Front-end parameter received: " + name);

        //2. Pass the result back to the front-end: Model
        model.addAttribute("msg", name);

        //3. View transition
        return "test";
    }
}

4. Change in Execution Result

When the input is empty, it will not return null but will display an error
http://localhost:8080/springmvc_04_controller_war_exploded/user/t1
Insert image description here
The result is the same when parameters are passed
http://localhost:8080/springmvc_04_controller_war_exploded/user/t1?username=zhangsan
Insert image description here
Insert image description here

5.2.1.4. The Submission is an Object

The form fields submitted should be consistent with the object properties; use an object as the parameter.

1. Entity Class: User.java
package com.kuang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data   // Lombok contains many convenience annotations that save a lot of underlying operations
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;

/*    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }*/
}
2. UserController.java
package com.kuang.controller;

import com.kuang.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/t1")      //localhost:8080/user/t1?name=...

    public String test1(@RequestParam("username") String name, Model model){
    // It's common to include @RequestParam("username") for frontend reception, so the URL changes to localhost:8080/username/t1?name=...

        //1. Receive frontend parameters (via name)
        System.out.println("Received frontend parameters: " + name);

        //2. Pass the returned result to the frontend: Model
        model.addAttribute("msg",name);

        //3. View redirection
        return "test";
    }

/*
1. Receive the parameters passed by the frontend user, check the parameter names; if the name is written directly on the method, it can be used directly.
2. If the passed object is a User, it matches the field names in the User object; it can only match successfully when the names are the same.
*/								
    // The frontend receives an object: id, name, age
    @GetMapping("/t5")
    public String test2(User user, Model model){
        System.out.println(user);
        System.out.println("000000"+user.toString());
        model.addAttribute("msg",user);
        return "test";
    }
}
3. Modify pom.xml
  • Add dependencies
    Modify SpringMVC_try1\SpringMVC_try1\springmvc-04-controller\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>com.kuang</groupId>
    <artifactId>SpringMVC_try1</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>springmvc-01-servlet</module>
        <module>springmvc-02-hello</module>
        <module>springmvc-03-hello-annotation</module>
        <module>springmvc-04-controller</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

<!-- Import dependencies -->
    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <!-- Import lombok library -->
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>

    </dependencies>


</project>

lombok的作用和常用注解_lombok注解-CSDN博客

4. Execution

http://localhost:8080/springmvc_04_controller_war_exploded/user/t5?id=20&name=zhangsan&age=99
Insert image description here

5.2.2. Displaying Data to the Frontend

5.2.2.1. First Method: Through ModelAndView

public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       // Return a ModelAndView object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

5.2.2.2. Second Method: Through ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
   // Encapsulate data to be displayed in the view
   // Equivalent to req.setAttribute("name",name);
   model.addAttribute("name",name);
   System.out.println(name);
   return "hello";
}

5.2.2.3. Third Method: Through Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
   // Encapsulate data to be displayed in the view
   // Equivalent to req.setAttribute("name",name);
   model.addAttribute("msg",name);
   System.out.println(name);
   return "test";
}

5.2.2.4. Comparison

Simply put, for beginners, the difference in use is:

  • Model has only a few methods and is only suitable for storing data, simplifying beginners’ operation and understanding of the Model object;
  • ModelMap extends LinkedMap and, in addition to its own methods, inherits the methods and features of LinkedMap;
  • ModelAndView, while storing data, can also set the return view, controlling the redirection of the presentation layer.
    Of course, more considerations in future development will be about performance and optimization, and it’s not limited to just this understanding.

The teacher’s advice: Spend 80% of your time laying a solid foundation, 18% studying frameworks, and 2% learning English. The official documentation of frameworks is always the best tutorial.

  • 20
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值