prepare123 prepare123 - 2 months ago 17
Java Question

How do I use a validator in Spring? I encountered a 500 error

How do I use a validator in Spring? I encountered a 500 error

-error details:


HTTPステータス 500 - Request processing failed; nested exception is
java.lang.IllegalStateException: An Errors/BindingResult argument is
expected to be immediately after the model attribute argument in the
controller method signature: public java.lang.String


-validator class:

public class loginvalidator implements Validator{

//交換できるオブジェクトなのか
@Override
public boolean supports(Class<?> clazz) {
return MemberModel.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object target, Errors errors) {

ValidationUtils.rejectIfEmpty(errors, "id", "id.empty");
ValidationUtils.rejectIfEmpty(errors, "password", "id.empty");

MemberModel membermodel= (MemberModel)target;

boolean patternCheck = Pattern.matches("^[a-zA-Z0-9]*$", membermodel.getPassword());
if(membermodel.getPassword().length()>4||patternCheck){
errors.rejectValue("password", "negativevalue");
}
}
}


-controller class -method:

@RequestMapping(value="loginaction", method=RequestMethod.POST)
public String loginaction(HttpServletRequest request, Model model, BindingResult bindingResult, MemberModel mmodel){

HttpSession session = request.getSession();
System.out.println("loginaction★★★★★★★★★"+bindingResult);
new loginvalidator().validate(mmodel, bindingResult);
if(bindingResult.hasErrors()){
return "redirect:/loginform?badpassword=true";
}

//로그인 로직 시행
int no = Integer.parseInt(request.getParameter("no"));
String password= request.getParameter("password");
System.out.println("loginaction 진입 아이디:"+no+" 비번: "+password);

MemberModel membermodel = m.login(no);
if(membermodel.getPassword().equals(password)){

ArrayList<MemberModel> list=m.memberlist();
System.out.println(list);
session.setAttribute("loginflag", "true");
session.setAttribute("name", membermodel.getName());
session.setAttribute("no", membermodel.getNo());
model.addAttribute("memberlist",list);

return "memberlist";
}else{
return "redirect:/loginform?failflag=true";
}
}

Answer

The problem you are facing is that model attribute parameter is expected before of BindingResult:

@ModelAttribute("mmodel") MemberModel mmodel, BindingResult result

Also, don't use @Valid in this case.

Comments