在春季启动时遇到有关验证器的问题

时间:2015-07-23 07:30:33

标签: validation spring-boot

我正在使用spring boot开发项目,我正在使用验证器来验证用户。

    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));
    }
}

这种方法运行正常。它在我调用此方法时验证用户。 但是当我在同一个控制器中调用另一个方法时,它给了我异常。

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)

在此控制器中给出异常的第二种方法是

 @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);
        }

我不想要对我的第二种方法进行验证,但是当我使用第二种方法进行验证时,它会给出上面指定的异常。 我的第二个问题是将来如果我想验证用户(使用对象映射器从地图中获取用户)在第二种方法中使用验证器然后如何做到这一点?

我的验证器类如下

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");
    }

}

1 个答案:

答案 0 :(得分:0)

您需要将参数传递给@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