gpt4 book ai didi

validation - 在 Spring Boot 中遇到有关验证器的问题

转载 作者:行者123 更新时间:2023-12-03 17:39:30 26 4
gpt4 key购买 nike

我正在 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));
}
}

这种方法工作正常。当我调用此方法时,它会验证用户。
但是当我在同一个 Controller 中调用另一个方法时,它给了我异常。
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)

在此 Controller 中给出异常的第二种方法是
 @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);
}

我不想验证我的第二种方法,但是当我点击第二种方法时,它给了我上面指定的异常。
我的第二个问题是将来如果我想使用验证器在第二种方法中验证用户(使用对象映射器从 map 中获取用户),那么该怎么做?

我的验证器类如下
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");
}

}

最佳答案

您需要将参数传递给 @InitBinder ,并在 @ModelAttribute 中使用它还有?在一个项目中,我在同一个 Controller 中使用了多个验证器,如下所示。那不是使用 @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

关于validation - 在 Spring Boot 中遇到有关验证器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31580845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com