Spring form submit validation for foreign key

General Tech Technology & Software 2 years ago

0 3 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Technology & Software related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (3)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

My project is a spring mvc project.In my project i have a domain Technology which has foreign key reference.When i validating on form submit it threw error....For view part(jsp),i using form:select for viewing department in technology. How can i validate a foreign reference????? i tried below code

domain

@Entity
@Table(name = "technology")
public class Technology {
private int id;
@NotEmpty
private String name;
@NotEmpty
private Department department;
private Date createdDate;
private boolean isDelete;
}

message.properties

NotEmpty.technology.department=Required!

Technology.jsp

 method="post" action="add-technology"
            commandName="technology" id="technologyForm">

            Technology Name
             path="name" />errors path="name" class="error">errors>
             />
            Department
             path="department.id">

                 value="0" label="Select" />

                 items="${departments}" itemValue="id" itemLabel="name" />

            errors path="department" class="error">errors>
            <%--    <form:select path="department.id" items="${departments}" /> --%>
             type="submit" class="btn btn-primary"/>

        

controller

@RequestMapping(value = "/add-technology")
public String addTechnology(
        @ModelAttribute(value = "technology")@Valid Technology technology,
        BindingResult result) {
    if(result.hasErrors()){
        return "/secure/admin/technology";
    }
    java.util.Date utilDate = new java.util.Date();
    Date sqlDate = new Date(utilDate.getTime());
    technology.setCreatedDate(sqlDate);

    technologyService.saveTechnology(technology);
    return "redirect:/technologies";
}

ERROR

org
                                                
                                                
0 views
0 shares
profilepic.png
manpreet 2 years ago

Here you have to implement validator for Technology object

class TechnologyValidator extends Validator {

    public boolean supports(Class cls) {
        return Technology .class.equals(cls);
    }

    public void validate(Object target, Errors errors) {
        super.validate(target, errors);
        Technology tecObj= (Technology ) target;
        //here i am assuming Technology name is REQUIRED and   
        //NotEmpty.technology.name is in message.properties
       ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name",
                                           "NotEmpty.technology.name");


      Department dept = tecObj.getDepartment();
      //as from from your are binding department ID
      if (dept==null || dept.getId()==null || dept.getId()==0L ) {
         errors.rejectValue("department.id", "NotEmpty.technology.department");
      }
  }
}

And create bean of this class in Spring-context

@Autowired
TechnologyValidator techValid;

And call this validator in your controller like

@RequestMapping(value = "/add-technology")
public String addTechnology(
        @ModelAttribute(value = "technology") Technology technology,
        BindingResult result) {

    //call validator
    techValid.validate(technology, result);

    if(result.hasErrors()){
        return "/secure/admin/technology";
    }
    java.util.Date utilDate = new java.util.Date();
    Date sqlDate = new Date(utilDate.getTime());
    technology.setCreatedDate(sqlDate);

    technologyService.saveTechnology(technology);
    return "redirect:/technologies";
}

0 views   0 shares

profilepic.png
manpreet 2 years ago

Here you have to implement validator for Technology object

class TechnologyValidator extends Validator {

    public boolean supports(Class cls) {
        return Technology .class.equals(cls);
    }

    public void validate(Object target, Errors errors) {
        super.validate(target, errors);
        Technology tecObj= (Technology ) target;
        //here i am assuming Technology name is REQUIRED and   
        //NotEmpty.technology.name is in message.properties
       ValidationUtils.rejectIfEmptyOrWhitespace(errors,"name",
                                           "NotEmpty.technology.name");


      Department dept = tecObj.getDepartment();
      //as from from your are binding department ID
      if (dept==null || dept.getId()==null || dept.getId()==0L ) {
         errors.rejectValue("department.id", "NotEmpty.technology.department");
      }
  }
}

And create bean of this class in Spring-context

@Autowired
TechnologyValidator techValid;

And call this validator in your controller like

@RequestMapping(value = "/add-technology")
public String addTechnology(
        @ModelAttribute(value = "technology") Technology technology,
        BindingResult result) {

    //call validator
    techValid.validate(technology, result);

    if(result.hasErrors()){
        return "/secure/admin/technology";
    }
    java.util.Date utilDate = new java.util.Date();
    Date sqlDate = new Date(utilDate.getTime());
    technology.setCreatedDate(sqlDate);

    technologyService.saveTechnology(technology);
    return "redirect:/technologies";
}

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community