首页 > 其他分享 >【WEEK2】 【DAY5】Data Processing and Redirection - Data Processing【English Version】

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

时间:2024-03-14 14:32:34浏览次数:28  
标签:DAY5 name Processing user org import Data public String

2024.3.8 Friday

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

Contents

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.

标签:DAY5,name,Processing,user,org,import,Data,public,String
From: https://blog.csdn.net/2401_83329143/article/details/136610456

相关文章

  • 【WEEK2】 【DAY5】数据处理及跳转之数据处理【中文版】
    2024.3.8Friday接上文【WEEK2】【DAY4】数据处理及跳转之结果跳转方式【中文版】目录5.2.数据处理5.2.1.提交处理数据5.2.1.1.提交的域名称和处理方法的参数名一致5.2.1.2.提交的域名称和处理方法的参数名不一致5.2.1.3.实例:新建文件1.UserController.java2.运......
  • pandas DataFrame内存优化技巧:让数据处理更高效
    Pandas无疑是我们数据分析时一个不可或缺的工具,它以其强大的数据处理能力、灵活的数据结构以及易于上手的API赢得了广大数据分析师和机器学习工程师的喜爱。然而,随着数据量的不断增长,如何高效、合理地管理内存,确保PandasDataFrame在运行时不会因内存不足而崩溃,成为我们每一个人......
  • C# EPPlus导出dataset----Excel2绘制图像
    一、生成折线图方法 ///<summary>    ///生成折线图    ///</summary>    ///<paramname="worksheet">sheet页数据</param>    ///<paramname="colcount">总列数</param>    ///<paramname="......
  • Vue学习日记 Day5
    一、路由(续)1、router-link:用于取代a标签 功能: 1、能跳转:配置to属性指定路径(必须),本质上还是a标签(使用to时无需#) 2、默认就会提供高亮类名,可以直接设置高亮样式 语法: <router-linkto="/find"></router-link> 作用: 会为需要高亮......
  • Database Connection Pool 数据库连接池-01-概览及简单手写实现
    拓展阅读第一节从零开始手写mybatis(一)MVP版本。第二节从零开始手写mybatis(二)mybatisinterceptor插件机制详解第三节从零开始手写mybatis(三)jdbcpool从零实现数据库连接池第四节从零开始手写mybatis(四)-mybatis事务管理机制详解连接池的作用资源重用由于数据库......
  • 高颜值且好用的自助发卡网站(idatariver.com)
    iDataRiver平台https://idatariver.com/zh-cn可支持商户无门槛入驻,可上架数字商品与API项目,本文介绍其数字商品的上架流程。感兴趣可直接前往官方文档术语解释数字商品数字商品是指可以自动交付的虚拟商品,例如:礼品卡、会员卡、授权/兑换码等等。数据项在实际操作中,......
  • 高颜值、免服务费、安全的自助发卡/数字商品寄售网站(idatariver.com)
    iDataRiver平台https://idatariver.com/zh-cn可支持商户无门槛入驻,使用usdt结算,可上架数字商品与API项目,本文介绍其数字商品的上架流程。感兴趣可直接前往官方文档术语解释数字商品数字商品是指可以自动交付的虚拟商品,例如:礼品卡、会员卡、授权/兑换码等等。数据项在实际......
  • datawhale-动手学数据分析task2笔记
    动手学数据分析task2数据清洗及特征处理缺失值观察与处理.isnull()和.isna()可判断表中所有缺失值,缺失值处为True,优先用.isna()。.isna().sum()可以获得columns的缺失值数量。.info()可以获得dataframe中columns的non-null值,从而推断出缺失值数量。.dropna()方法可......
  • 【DataWhale学习】用免费GPU线上跑StableDiffusion项目实践
    用免费GPU线上跑SD项目实践​DataWhale组织了一个线上白嫖GPU跑chatGLM与SD的项目活动,我很感兴趣就参加啦。之前就对chatGLM有所耳闻,是去年清华联合发布的开源大语言模型,可以用来打造个人知识库什么的,一直没有尝试。而SD我前两天刚跟着B站秋叶大佬和Nenly大佬的视频学习过......
  • 阿里云数据湖存储加速套件JindoData
      计算存储分离已经成为云计算的一种发展趋势。在计算存储分离之前,普遍采用的是传统的计算存储相互融合的架构,但是这种架构存在一定的问题,比如在集群扩容的时候会面临计算能力和存储能力相互不匹配的问题。用户在某些情况下只需要扩容计算能力或者存储能力,而传统的融合架构......