как исправить проверку формы, когда она не работает - PullRequest
0 голосов
/ 01 августа 2020

Мне нужна ваша помощь, проверка формы не работает, после нескольких статей он все еще не работает

вот мой пом. xml

<?xml version="1.0" encoding="UTF-8"?>

4.0.0 org .springframework.boot spring-boot-starter-parent 2.3.2.RELEASE com.king Gestpeacesecurity 0.0.1-SNAPSHOT Проект мирной безопасности Gestpeacesecurity для Spring Boot

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf</artifactId>
      <version>3.0.11.RELEASE</version>
    </dependency>
    
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring4</artifactId>
      <version>3.0.11.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>nz.net.ultraq.thymeleaf</groupId>
      <artifactId>thymeleaf-layout-dialect</artifactId>
      <version>2.4.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </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.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency> -->
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Мой агент ie Агент, я использую lomback для геттера и сеттера

package com.king.Entities;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.format.annotation.DateTimeFormat;

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

@Entity
@Data @NoArgsConstructor @AllArgsConstructor
public class Agent implements Serializable {
    @Id 
    @NotNull
    @Size(min=5,max=5)
    private  String matricule;
    @NotNull
    @Size(min=4,max=15)
    private String nom;
    private String prenom;
    private String postnom;
    private String fonction;
    private String typeagent;
    private String niveaetude;
    private String contact1;
    private String contact2;
    private String sexe;
    private String adresse1;
    private String adresse2;
    private String photo;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date dateNaiss;
    private String lieuNais;
    private String status;
}

это мой контроллер

@RequestMapping(value="/showFormAgent", method = RequestMethod.GET)
public String showFormAgent(Model model) {
    model.addAttribute("agent", new Agent());
    return "peacedrh/formAgent";
}

@RequestMapping(value="addAgent", method = RequestMethod.POST)
public String addAgent(@RequestParam(name="picture")MultipartFile file, Model model, String matricule, @Valid Agent A, BindingResult result) {
    
    
    try {
        if (!(file.isEmpty())) {
            A.setPhoto(file.getOriginalFilename());
        }
        agentDao.AddAgent(matricule, A);
        
        if (!(file.isEmpty())) {
            A.setPhoto(file.getOriginalFilename());
            file.transferTo(new File (imageDir+A.getMatricule()));
            
        }
        
    } catch (Exception e) {
        // TODO: handle exception
        model.addAttribute("error", e);
        return  "redirect:/showFormAgent?matricule="+matricule+"&error="+e.getMessage();        
    }
    model.addAttribute("agent", agentDao.getBymatricule(matricule));
    return "peacedrh/Accuse";
    
}

это моя html страница (тимелист)

<form role="form"  method="post" th:action="@{addAgent}" th:object="${agent}" enctype="multipart/form-data">
                      <div class="card-body">
                      <div class="form-group">
                                        <label for="exampleInputEmail1">Matricule</label>
                                        <input type="text" th:field="*{matricule}" class="form-control" id="exampleInputEmail1" placeholder="Enter Matricule"/>
                                        <span class="text-danger" th:errors="*{matricule}">  </span>
                                    </div>
                        <div class="row">
                            <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="exampleInputEmail1">Nom</label>
                                        <input type="text" th:field="*{nom}" class="form-control" id="exampleInputEmail1" placeholder="Enter Nom"/>
                                        <span class="text-danger" th:errors="*{matricule}">  </span>
                                        
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Post nom</label>
                                        <input type="text" th:field="*{postnom}"  class="form-control" id="exampleInputPassword1" placeholder="Post nom"/>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Prenom</label>
                                        <input type="text" th:field="*{prenom}"  class="form-control" id="exampleInputPassword1" placeholder="Prenom"/>
                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Sexe</label>
                                        <select th:field="*{sexe}">
                                            <option value="M">M</option> 
                                            <option value="F">F</option>
                                        </select>
                                    </div>
                                    <div class="input-group mb-3">

                                    <div class="form-group">
                                        <label for="exampleInputPassword1">Statut Sociale</label>
                                        <select th:field="*{status}">
                                            <option value="Single">Single</option> 
                                            <option value="Maried">Maried</option>
                                            <option value="Veuve">Veuve</option>
                                            <option value="Veuf">Veuf </option>
                                            <option value="Divorce">Divorce</option>
                                            <option value="separe">Separe(é)</option>
                                            
                                        </select>
                                    </div>
                                       <div class="form-group">
                                        <label for="exampleInputPassword1">Lieu de naissance</label>
                                        <input type="text" th:field="*{lieuNais}"  class="form-control" id="exampleInputPassword1" placeholder="Lieu de naissance"/>
                                    </div>
                                      <div class="form-group">
                                        <label for="exampleInputPassword1">Date de naissance</label>
                                        <input type="date"  th:field="*{dateNaiss}"  class="form-control"/>
                                  </div>
                                  <div class="form-group">
                                     <label for="exampleInputPassword1">Niveau Etudet</label>
                                     <input type="text" th:field="*{niveaetude}"  class="form-control" id="exampleInputPassword1" placeholder="Niveau d'étude"/>
                                </div>
                                <div class="form-group">
                                      <label for="exampleInputPassword1">Type Agent</label>
                                      <select th:field="*{typeagent}">
                                            <option value="Admin">Admnistratif</option> 
                                            <option value="Terrain">Terrain</option>
                                       </select>
                                 </div>
                               </div>
                           </div>
                                  
                        
                            <div class="col-md-6">
                                
                                 <div class="form-group">
                                    <label for="exampleInputPassword1">Fonction</label>
                                     <select th:field="*{fonction}">
                                            <option value="Comptable">Comptable</option> 
                                            <option value="DRH">Direc Res Hum</option>
                                       </select>
                                 </div>
                                 <div class="form-group">
                                      <label for="exampleInputPassword1">Contact 1</label>
                                      <input type="text" th:field="*{contact1}"  class="form-control" id="exampleInputPassword1" placeholder="Contat 1"/>
                                 </div>
                                 <div class="form-group">
                                      <label for="exampleInputPassword1">Contact 2</label>
                                      <input type="text" th:field="*{contact2}"  class="form-control" id="exampleInputPassword1" placeholder="Contact 2"/>
                                 </div>
                                 <div class="form-group">
                                    <label for="exampleInputFile">File input</label>
                                 <div class="input-group">
                                 <div class="custom-file">
                                    <input type="file"  name="picture"  class="custom-file-input" id="exampleInputFile"/>
                                    <label class="custom-file-label" for="exampleInputFile">Choose file</label>
                                  </div>
                                </div> 
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">Adresse 1</label>
                                    <textarea  th:field="*{adresse1}"  class="form-control" rows="5" cols="5"></textarea>
                             </div>
                             <div class="form-group">
                                    <label for="exampleInputPassword1">Adresse 2</label>
                                    <textarea  th:field="*{adresse2}"  class="form-control" rows="5" cols="5"></textarea>
                             </div>
                            </div>
                            
                        </div>
                        <div class="card-footer">
                            <div class="row col-md-5 ml-20" >
                                <div class="col-md-6"><button type="submit" class="btn btn-primary">Submit</button></div>
                                <div class="col-md-6"><button type="reset" class="btn btn-primary">Cancel</button></div>
                            </div>
                         </div>
                      </form>

добавление идет хорошо но проверка формы по-прежнему не работает

1 Ответ

0 голосов
/ 01 августа 2020

Вы должны добавить @RequestBody, потому что хотите запросить форму из представления:

@Valid Agent A

Becomes

   @Valid @RequestBody Agent A

В противном случае вы можете передать объект Agent как @ModelAttribute на вашем showFormAgent

public String showFormAgent(@ModelAttribute Agent A) {
    return "peacedrh/formAgent";
}

, а затем просто получите данные из вашего addAgent

@RequestMapping(value="addAgent", method = RequestMethod.POST)
public String addAgent(@ModelAttribute @Valid Agent A, BindingResult result) { //doSomething }

, а BindingResult содержит результат проверки, поэтому вам нужно проверить, есть ли у вас ошибки или нет:

if (result.hasErrors()) {
   return "previus_form";
} else {
   return "success";
}
...