不从控制器类调用Validate方法

时间:2018-04-04 10:30:51

标签: java spring

验证方法不是从控制器类调用的,而是直接执行的返回语句。自定义验证未执行。

控制器类:

package com.cluster;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {

  @RequestMapping("/")
  public ModelAndView index() {

  User user = new User();
    return new ModelAndView("index","user",user);
  }

  @RequestMapping(value="/display")
  public String  display(Model model, @ModelAttribute("user")User 
      user,BindingResult result) {

    System.out.println("intocontroller");
    UserValidator userValidator = new UserValidator();
    userValidator.validate(user, result);
    if(result.hasErrors()) {
      System.out.println("into error loop");
      return "index";
    }
    return "redirect:/check";
  }

  @RequestMapping(value="/check")
  public ModelAndView check() {
    return new ModelAndView("success");
  }
}

验证员类:

package com.cluster;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class UserValidator implements Validator{

  @Override
  public boolean supports(Class clazz){

    return User.class.equals(clazz);
  }

  @Override // getting object and bindingresult reference 
  public void validate(Object target,Errors errors) {

    User user =(User)target;
    if(user.getFname()==null){
      errors.rejectValue("fname","Name shouldnt be null");
    }
    //validating the field
    if(user.getLname()==null){      
      errors.rejectValue("lname","Name shouldnt be null");
    }
  }
}

POJO课程:

package com.cluster;

public class User {

  private String fname;
  private String lname;

  public String getFname() {
    return fname;
  }
  public void setFname(String fname) {
    this.fname = fname;
  }
  public String getLname() {
    return lname;
  }
  public void setLname(String lname) {
    this.lname = lname;
  }
}

它进入控制器方法但用户验证类的对象没有执行。

请向我解释如何在Stack Overflow上发布问题,它告诉我格式化代码。

1 个答案:

答案 0 :(得分:0)

尝试使用实体侦听器

documentation

Example