springboot + thymeleaf réalise la soumission d'informations de formulaire et la fonction d'affichage

Créer un projet d'initialisation Spring

Cliquez sur Fichier-> Nouveau-> Projet, sélectionnez Spring Initalizr, sélectionnez la version JDK, cliquez sur Suivant

Créer un projet
Entrez des informations personnalisées dans cette fenêtre et cliquez sur Suivant

Créer un projet
Sélectionnez Web-> Spring Web, cliquez sur Suivant

Créer un projet
Entrez le nom du projet, cliquez sur Terminer pour terminer la création

Créer un projet
Une fois la création terminée, le contenu suivant apparaîtra dans le coin inférieur droit, sélectionnez Activer l'importation automatique, afin que IDEA puisse automatiquement nous aider à importer le contenu dont nous avons besoin

Configuration automatique

Importer la dépendance

Dans ce projet, ajoutez simplement une autre dépendance thymeleaf dans pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Le code pom.xml complet est le suivant

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.form</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>FormDemo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Écrire la page d'entrée

Créez le fichier input.html dans src-> main-> resources-> templates (la recherche de pages statiques dans la configuration suivante les trouvera automatiquement sous ce fichier)

Notez que thymeleaf doit être chargé dans le fichier d'en-tête ici

<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

Le code complet est le suivant

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>个人信息填写</title>
</head>
<body>
    <form th:action="@{/out}" method="post">
    //此处的@{/out}会自动进入后面创建的PersonController.java文件中用@RequestMapping("out")注解的方法
        姓名:<input type="text" name="name"><br><br>
        性别:<input type="radio" name="sex" value="女"><input type="radio" name="sex" value="男"><br><br>
        年龄:<input type="text" name="age"><br><br>
        学历:<select name="education">
                <option value="小学">小学</option>
                <option value="初中">初中</option>
                <option value="高中">高中</option>
                <option value="本科">本科</option>
                <option value="研究生">研究生</option>
                <option value="博士">博士</option>
             </select><br><br>
        个人简介:<textarea name="information" rows="10" cols="20"></textarea><br><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

Ecrire des classes d'entités

Créez Person.java sous src-> main-> java-> comp> bean, ajoutez des attributs, des méthodes de construction, etc. Le code complet est le suivant

package com.bean;
public class Person {
    
    
    private String name;
    private String sex;
    private int age;
    private String education;
    private String information;
    public Person(String name, String sex, int age, String education, String information) {
    
    
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.education = education;
        this.information = information;
    }
    @Override
    public String toString() {
    
    
        return "Person{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", education='" + education + '\'' +
                ", information='" + information + '\'' +
                '}';
    }
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    public String getSex() {
    
    
        return sex;
    }
    public void setSex(String sex) {
    
    
        this.sex = sex;
    }
    public int getAge() {
    
    
        return age;
    }
    public void setAge(int age) {
    
    
        this.age = age;
    }
    public String getEducation() {
    
    
        return education;
    }
    public void setEducation(String education) {
    
    
        this.education = education;
    }
    public String getInformation() {
    
    
        return information;
    }
    public void setInformation(String infromation) {
    
    
        this.information = information;
    }
}

Classe de contrôle d'écriture

Créez PersonController.java dans src-> main-> java-> com> config pour terminer la fonction de transfert des données du formulaire. Le code complet est le suivant

package com.config;
import com.bean.Person;
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
public class PersonController {
    
    
    @RequestMapping("out")
    //此处与前面input.html中th:action="@{/out}"对应
    public String outputmessage(@RequestParam("name") String name,
                                @RequestParam("sex") String sex,
                                @RequestParam("age") int age,
                                @RequestParam("education") String education,
                                @RequestParam("information") String information,
                                //此注解用于接收表单传递的内容
                                Model model){
    
    
        Person person = new Person(name,sex,age,education,information);
        model.addAttribute("myperson",person);
        //将自定义的person实体添加到model模型中,方便后面获取
        return "output";
        //转入output.html页面
    }
}

Ecrire une classe pour contrôler le chemin de l'URL

Ajoutez hello.java dans src-> main-> java-> com> config. La fonction de ce fichier est de transférer automatiquement vers la page statique input.html sous templates lorsque l'url d'entrée est localhost: 8080 / input
. Le code complet est le suivant

package com.config;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class hello {
    
    
    @RequestMapping("input")
    //input可随意更改
    public String input(){
    
    
        return "input";
        //转入input.html页面
    }
}

Écrire la page de sortie

Pour créer le fichier output.html dans src-> main-> resources-> templates, vous devez également introduire le code complet de thymeleaf comme suit

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>个人信息</title>
</head>
<body>
    <h2>姓名:</h2><h3 th:text="${myperson.name}"></h3>
    <h2>性别:</h2><h3 th:text="${myperson.sex}"></h3>
    <h2>年龄:</h2><h3 th:text="${myperson.age}"></h3>
    <h2>学历:</h2><h3 th:text="${myperson.education}"></h3>
    <h2>个人简介:</h2><h3 th:text="${myperson.information}"></h3>
    //通过我们之前保存在model中的myperson实体获取表单中的内容
</body>
</html>

Vérifions le résultat

Entrez localhost: 8080 / input dans le navigateur, entrez les données et les résultats sont les suivants

Page d'entrée
Après soumission, les informations saisies s'affichent correctement

Informations de sortie

Je suppose que tu aimes

Origine blog.csdn.net/qq_44042316/article/details/104131977
conseillé
Classement