spring comes with an interceptor

Code from Spring in action page 165

Adding annotations to pojo, I personally think that the writing workload is quite large, and the code intrusion is relatively high.

 

public class Spitter {

  private Long id;
  
  @NotNull
  @Size(min=5, max=16)
  private String username;

  @NotNull
  @Size(min=5, max=25)
  private String password;
  
  @NotNull
  @Size(min=2, max=30)
  private String firstName;

  @NotNull
  @Size(min=2, max=30)
  private String lastName;
  
  @NotNull
  @Email
  private String email;

  --------------------------------------------
//below are the setter and getter methods

 

Validation at the control level

 

package spittr.web;

import static org.springframework.web.bind.annotation.RequestMethod.*;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import spittr.Spitter;
import spittr.data.SpitterRepository;

@Controller
@RequestMapping("/spitter")
public class SpitterController {
  @RequestMapping(value="/register", method=POST)
  public String processRegistration(
      @Valid Spitter spitter,
      Errors errors) {
    if (errors.hasErrors()) {
      return "registerForm";
    }
    spitterRepository.save(spitter);
    return "redirect:/spitter/" + spitter.getUsername();
  }

  

 

The transmitted form data is converted into pojo and validated. If there is an error, put the error in Errors errors, and then judge the errors in the control layer. If there is an error, go back to the submit form page, and if it is correct, jump to the correct page.

 

If the company likes to write if in the control layer to judge, then write if statement.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326182880&siteId=291194637