当前位置: 首页 > 知识库问答 >
问题:

Spring boot:如何在springboot中验证多部分表单

贡和裕
2023-03-14

当尝试验证表单(获取请求)时,我知道Result绑定,当尝试验证请求正文时,我也知道@Valid,但我不知道如何验证multipartForm Request参数。当我将json转换为对象时,我有一个带有请求参数@Request estParam("model")String userJson的多部分表单,其中包含我的User.class.的json字符串表示形式,

User user = new Gson().fromJson(userJson, User.class);

如何检查user类中的参数是否满足要求,例如(电子邮件中有'@'或名字没有数字值)?

这是我的代码,控制器:

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public ResponseEntity<ResponseModel> SignUp(@RequestParam("file") MultipartFile file, @RequestParam("model") String userJson, RedirectAttributes redirectAttributes){

        User tempSavedUser = new User();

        try {

                if (file.isEmpty()) {
                    redirectAttributes.addFlashAttribute("message", "Please select a file to upload");

                

        responseModel.setIsSuccessful(false).setResponseMessage("Please select an image to upload");
    
                        return new ResponseEntity<>(responseModel, HttpStatus.CREATED); // return response to client.
                    }
    
                    User user = new Gson().fromJson(userJson, User.class);
    tempSavedUser = this.defaultUserDAOService.saveUser(user);
responseModel.setIsSuccessful(true);

                        responseModel.setResponseMessage("Registration was successful, Please check your mail for an account activation link");

                        return new ResponseEntity<ResponseModel>(responseModel, HttpStatus.CREATED);
    }

这是用户类,用于:

@Table(name = "Users")
public class User extends DefaultEntity {


    @Column(name = "FirstName")
    @NotNull(message = "Enter a FirstName")
    private String firstName;


    @Column(name = "LastName")
    @NotBlank(message = "Enter a LastName")
    private String lastName;


    @Column(unique = true,name = "UserName")
    @NotBlank(message = "Enter a UserName")
    private String userName;


    @Column(unique = true, name = "Email")
    @NotBlank(message = "Please enter an Email address")
    @Email(message = "Enter a valid Email")
    private String email;


    @Column(name = "Password")
    @NotBlank(message = "Enter a Password")
    private String password;


    @Enumerated(EnumType.STRING)
    @Column(name = "Gender")
    private Gender gender;


    @Column(name = "Address")
    @NotBlank(message = "Please enter your Home Address")
    private String address;


    @Column(name = "Country")
    @NotBlank(message = "Please enter your Country")
    private String country;


    @Column(name = "Picture")
    private String picture;


    @Column(unique = true, name = "PhoneNumber") //make this accept only numbers
    private String phoneNumber;


    @Column(name = "Bio")
    private String bio;


    @Enumerated(EnumType.STRING)
    @Column(name = "OnlineStatus")
    private OnlineStatus onlineStatus;

    @Enumerated(EnumType.STRING)
    @Column(name = "UserType")
    private UserType userType;


    @Column(name = "Money")
    private double money;


    //@MapsId()
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "playerstats")
    private PlayerStats playerStats;

    //columnDefinition = "tinyint default false"
    @Column(name = "locked",columnDefinition = "BOOL default false")
    private Boolean locked;


    @Transient
    private MultipartFile file;


    public String getFirstName() {
        return firstName;
    }

    public User setFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public String getLastName() {
        return lastName;
    }

    public User setLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

    public String getUserName() {
        return userName;
    }

    public User setUserName(String userName) {
        this.userName = userName;
        return this;
    }

    public String getEmail() {
        return email;
    }

    public User setEmail(String email) {
        this.email = email;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public User setPassword(String password) {
        this.password = password;
        return this;
    }

    public Enum.Gender getGender() {
        return gender;
    }

    public User setGender(Enum.Gender gender) {
        this.gender = gender;
        return this;
    }

    public String getAddress() {
       return address;
    }

    public User setAddress(String address) {
       this.address = address;
       return this;
    }

    public String getCountry() {
        return country;
    }

    public User setCountry(String country) {
        this.country = country;
        return this;
    }

    public String getPicture() {
        return picture;
    }

    public User setPicture(String picture) {
        this.picture = picture;
        return this;
    }

    public String getBio() {
        return bio;
    }

    public User setBio(String bio) {
        this.bio = bio;
        return this;
    }

    public Enum.OnlineStatus getOnlineStatus() {
        return onlineStatus;
    }

    public User setOnlineStatus(Enum.OnlineStatus onlineStatus) {
        this.onlineStatus = onlineStatus;
        return this;
    }

    public Enum.UserType getUserType() {
        return userType;
    }

    public User setUserType(Enum.UserType userType) {
        this.userType = userType;
        return this;
    }

    public double getMoney() {
        return money;
    }

    public User setMoney(double money) {
        this.money = money;
        return this;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public User setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
        return this;
    }

    public MultipartFile getFile() {
        return file;
    }

    public User setFile(MultipartFile file) {
        this.file = file;
        return this;
    }

    public PlayerStats getPlayerStats() {
        return playerStats;
    }

    public User setPlayerStats(PlayerStats playerStats) {
        this.playerStats = playerStats;
        return this;
    }

    public Boolean getLocked() {
        return locked;
    }

    public void setLocked(Boolean locked) {
        this.locked = locked;
    }

}

共有1个答案

文自怡
2023-03-14

为了使用spring验证多部分表单,您可以采取以下方法:

  • 包括用于上传MultipartFile的Commons-fileupload。
  • 包含验证api以创建验证器。

作为:

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>
  <dependency>
   <groupId>javax.validation</groupId>
   <artifactId>validation-api</artifactId>
   <version>1.1.0.Final</version>
</dependency>
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {
    "com.test"
})
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }

    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
        rb.setBasenames(new String[] {
            "validation"
        });

        return rb;
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver getResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        //set max upload size per file is 20mb
        commonsMultipartResolver.setMaxUploadSizePerFile(20 * 1024 * 1024);

        return commonsMultipartResolver;
    }
}
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class << ? > [] getRootConfigClasses() {
        return new Class[] {
            WebConfig.class
        };
    }

    @Override
    protected Class << ? > [] getServletConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
            "/"
        };
    }
}
public class Model {
    private User user;
    private CommonsMultipartFile[] files;
    //getter and setter
}
@Component
public class ModelValidator implements Validator {

    public boolean supports(Class << ? > clazz) {
        return Model.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        Model model = (Model) target;

        CommonsMultipartFile[] commonsMultipartFiles = model.getFiles();

        for (CommonsMultipartFile multipartFile: commonsMultipartFiles) {
            if (multipartFile.getSize() == 0) {
                errors.rejectValue("files", "myapplication.missing.file");
            }
        }
    }
}
myapplication.missing.file=No file choose
@Controller
@RequestMapping(value = "/")
public class Controller {

    @Autowired
    ModelValidator modelValidator;

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public ModelAndView page() {
        ModelAndView model = new ModelAndView("page");
        model.addObject("model", new Model());

        return model;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView upload(@ModelAttribute("model") Model model, BindingResult result) throws IOException {
        // :::: VALIDATION HAPPENS HERE ::::
        fileValidator.validate(model, result);

        if (result.hasErrors()) {
            return new ModelAndView("page");
        }

        return new ModelAndView("success", "fileNames", processUpload(model));
    }

    private List < String > processUpload(Model model) throws IOException {
        List < String > Models = new ArrayList < String > ();

        CommonsMultipartFile[] commonsMultipartFiles = model.getFiles();

        for (CommonsMultipartFile multipartFile: commonsMultipartFiles) {
            FileCopyUtils.copy(multipartFile.getBytes(), new File("C:\\upload\\" + multipartFile.getOriginalFilename()));
            fileNames.add(multipartFile.getOriginalFilename());
        }

        return fileNames;
    }
}

https://memorynotfound.com/spring-mvc-file-upload-example-validator/http://websystique.com/springmvc/spring-mvc-4-fileupload-download-hibernate-example/http://javainsimpleway.com/spring-mvc-file-upload-with-validation/

 类似资料:
  • 在尝试使用JSR-303(hibernate Validator)验证模型时,我在将

  • 我有一个DTO,它在控制器层通过BeanValidation(javax.validation)和定制验证器(org.springframework.validation.Validator)的组合进行验证。通过这种方式,我可以检查提供的输入是否有效,然后转换实体中的DTO并将其转发到服务层。 然后是业务逻辑验证。例如:@Entity用户的startDate必须在某个事件发生之后,如果最后创建的用

  • 我有一个简单的springboot应用程序和一个Rest api。我想验证请求参数不为null/空。我将json转换成一个java对象,并从这里开始验证它们是否包含所有必需的字段,并且不为null或不为空。(对象没有保存到db)我目前正在使用javax验证方法,但是没有成功。 我还有一个包含的要素类,我需要验证(所有字段均为必填字段,而不是空或空)

  • 我在Spring Boot web应用程序中有一个非常特殊的要求:我有内部和外部用户。内部用户通过使用KeyCoap身份验证登录到web应用程序(他们可以在web应用程序中工作),但我们的外部用户通过简单的Spring Boot身份验证登录(他们可以做的只是下载web应用程序生成的一些文件) 我想做的是使用多个身份验证模型:除了/download/*之外的所有路径都要通过我们的keyCoap身份验

  • 我试图创建一个页面,用户可以张贴图像及其细节。现在,当我测试来自postman的spring boot服务时,我能够成功地在服务中获取文件。当我试图从angular5中做同样的事情时,多部分文件在服务中没有被识别,并且总是得到空数组。 我的角服务代码如下 } 我已经尝试添加标头,如multipart/form-data,并将其设置为un定义。无论哪种方式,我都收到了错误。在发布到这里之前,我已经广

  • 本文向大家介绍SpringBoot集成kaptcha验证码,包括了SpringBoot集成kaptcha验证码的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了SpringBoot集成kaptcha验证码的具体代码,供大家参考,具体内容如下 1.kaptcha相关介绍 Kaptcha是一个基于SimpleCaptcha的验证码开源项目。 2.集成方案 ①pom.xml中配置依赖 ②配置