Validator issue on spring boot

I am developing a project in spring boot and I am using validator to validate the user.

    import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.newDemo.common.service.ResourceProperties;
import com.newDemo.constants.Constant;
import com.newDemo.modules.user.domain.AuthenticationToken;
import com.newDemo.modules.user.domain.User;
import com.newDemo.modules.user.service.AuthenticationTokenService;
import com.newDemo.modules.user.service.SocialAuthService;
import com.newDemo.modules.user.service.UserService;
import com.newDemo.modules.user.validator.UserValidator;
import com.newDemo.utils.ResponseHandlerUtil;

@RestController
@RequestMapping("/api/v1/user")
public class UserController {

    public static Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired UserService userService;
    @Autowired AuthenticationTokenService authenticationTokenService;
    @Autowired SocialAuthService socialAuthService;
    @Autowired ResourceProperties resourceProperties;
    private Properties configProp;

    /**
     * load message property file
     * @throws IOException
     */
    @PostConstruct
    public void init() throws IOException{
        configProp = resourceProperties.getResourceProperties(Constant.RESPONSE_MSG_FILE_PATH);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UserValidator());
    }

    /**
     * this method used to create new user or update user
     * @author oodles
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public Map<String, Object> addUser(@Valid @RequestBody User user) {
        log.debug("adding new user");
        return ResponseHandlerUtil.generateResponse(
                configProp.getProperty("user.created"), HttpStatus.ACCEPTED,
                true, userService.addUser(user));
    }
}

This method is working fine. It validates the user when I call this method. But when I call another method in the same controller, it gives me an exception.

java.lang.IllegalStateException: Invalid target for Validator [com.newDemo.modules.user.validator.UserValidator@6582b808]: {social_auth_token=CAACEdEose0cBAGXgjErY8fPJQNqPzSpMoU2FagZBLgOo4P7xtpoJgWSEOAINrmj4HTBuhUKpO5jQBYTH3z2jq92kog90R1qzXBKmZC7OEEXN8gaZBuNqZBYN9iPSoKLL9ZAcTgojRkcz2dQjcJTAhvq7NG8PoK9ZAvShYKN5QOmimI5ZALNMxqasFBZBaZBHUKb4yBClcWA9AUMWdzDQYRWqnZAsIrmhN78zcZD, login_type=facebook, userdetails={socialId=661252653921786, email=qsiddiqui81@gmail.com, username=qsiddiqui81@gmail.com, age=20, firstName=Qasim, lastName=Siddiqui, gender=male, address={city=gurgaon, state=Haryana}}}
    at org.springframework.validation.DataBinder.assertValidators(DataBinder.java:516)
    at org.springframework.validation.DataBinder.setValidator(DataBinder.java:507)
    at com.newDemo.modules.user.controller.UserController$$EPJF5LJA.initBinder(UserController.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

The second method that throws an exception in this controller is

 @RequestMapping(value = "/sociallogin", method = RequestMethod.POST)
        public Map<String, Object> login(@RequestBody Map map,HttpServletResponse resp) throws IOException{
                Map<String, Object> data = null;
                final ObjectMapper mapper = new ObjectMapper();
User user = (User)mapper.readValue(mapper.writeValueAsString(map.get("userdetails")), User.class);
                data = socialAuthService.login((String) map.get("social_auth_token"), (String) map.get("login_type"), user);
            return ResponseHandlerUtil.generateResponse(configProp.getProperty("login.success"),HttpStatus.ACCEPTED, true, data);
        }

I do not want to check my second method, but when I hit the second method, it gives me the above exception. And my second question in the future, if I want to check on a user (selecting a user from the map using the mapper object) in the second method using the validator, then how to do this?

My validator class is as follows

package com.newDemo.modules.user.validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.newDemo.modules.user.domain.User;

public class UserValidator implements Validator{

    public static Logger log = LoggerFactory.getLogger(UserValidator.class);
    @Override
    public boolean supports(Class<?> clazz) {
        // TODO Auto-generated method stub
        return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors err) {
        // TODO Auto-generated method stub
        log.debug("validating user");
        ValidationUtils.rejectIfEmptyOrWhitespace(err, "email", "email.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(err, "username", "username.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(err, "password", "password.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(err, "firstName", "firstName.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(err, "gender", "gender.empty");
    }

}
+4
source share
1 answer

@InitBinder @ModelAttribute? , . @RequestBody.

@InitBinder("signupForm")
protected void initSignupBinder(WebDataBinder binder) {
    binder.setValidator(signupFormValidator);
}

@InitBinder("forgotPasswordForm")
protected void initForgotPasswordBinder(WebDataBinder binder) {
    binder.setValidator(forgotPasswordFormValidator);
}

@InitBinder("resetPasswordForm")
protected void initResetPasswordBinder(WebDataBinder binder) {
    binder.setValidator(resetPasswordFormValidator);
}

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(@ModelAttribute("signupForm") @Valid SignupForm signupForm,
        BindingResult result, RedirectAttributes redirectAttributes) {

... more methods
0

Source: https://habr.com/ru/post/1599239/


All Articles