2

I am aware of ResultBinding when trying to validate a form (get request), i am also aware of @Valid when trying to validate a request body but i have no knowledge of validating a multipartForm Request parameter. I have a multipart form with a request parameter @RequestParam("model") String userJson of a json string representation of my User.class. when i convert the json to an object,

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

how can i check if the parameters in the user class meets requirements, such as (email having an '@' or first name not having numeral values) ?

This is my code, the controller :

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

this is the user class to:

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

}
7
  • You need to provide proper details with code examples of what exactly you are trying to do. Commented Sep 3, 2018 at 15:45
  • your question is not clear but I send you the most appropriate way to validate mulipart form Commented Sep 3, 2018 at 16:32
  • @MohammadRezaAlagheband okay sir, i will also update my code Commented Sep 3, 2018 at 18:38
  • @jbx please check out the code, i have updated it Commented Sep 3, 2018 at 18:43
  • @MohammadRezaAlagheband i just want to validate the User model after i parse Commented Sep 3, 2018 at 18:45

1 Answer 1

4

Inorder to validate a multipart form with spring you can take take this approach :

  1. Add Dependencies

  • include the commons-fileupload which is used to upload a MultipartFile.
  • include the validation-api to create a Validator.

As:

<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>

2.Create a Web Config:

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

3.Create WebInitializer Class which extends from AbstractAnnotationConfigDispatcherServletInitializer

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[] {
            "/"
        };
    }
}
  1. Create Your Model

public class Model {
    private User user;
    private CommonsMultipartFile[] files;
    //getter and setter
}

5.Create a Validator to validate you file

@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");
            }
        }
    }
}
  1. Add validation error message in side application.properties under resources folder

myapplication.missing.file=No file choose
  1. Develop a controller

@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 ::::
        modelValidator.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;
    }
}

More Information:

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Author asked for the springboot and you are providing solution for Spring mvc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.