0

我有一个使用encType="multipart/form-data"的Spring MVC应用程序。该表单是一个用户注册表单,其中包含图像以及其他字段,例如用户名、名字、姓氏、dob ect。然后将表单提交给控制器,控制器通过@InitBinder注释调用验证。

当文件发布到处理验证的类时,所有值都是NULL。我读到这会发生,因为标签中的 encType ="multipart/form-data"<form>。我也在 applicationcontext.xml 中使用这个 bean 定义:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="157286400" />
    <property name="maxInMemorySize" value="5242880"/>
    <property name="defaultEncoding" value="utf-8"/>
</bean>

有人可以给我一个例子,说明我如何从这个文件中提取值并验证它们。我不确定如何在验证器类中接收数据并处理其内容。

验证类

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.crimetrack.business.Citizens;


@Component
public class CitizenRegistrationValidation implements Validator{

    private final Logger logger = Logger.getLogger(getClass());

    private @Autowired HttpServletRequest request;


    public boolean supports(Class<?> clazz) {

        return Citizens.class.equals(clazz);
    }

    public void validate(Object target, Errors errors) {


            Citizens citizens = (Citizens)target;   

//---------------------------------------------------------------------------------------------


    String user_request =  request.getParameter("user_request");
    String photo = request.getParameter("photo");   


    logger.info("Thee request param for photo is :"+ photo);
    logger.info("About to validate citizen");
    logger.info("The user request was " + user_request);

    if (!user_request.equals("New")){
        if (user_request.equals("Save") || user_request.equals("update")){

                if(citizens.getSocialSecurityNumber() == 0){

                    errors.rejectValue("socialSecurityNumber", "socialSecurityNumber.required");

                }



                if (citizens.getCitizenTypeId() == 1){

                    errors.rejectValue("citizenTypeId", "citizenTypeId.required");
                }

                if(citizens.getfName() == null){

                    errors.rejectValue("fName", "fName.required");
                }

                if (citizens.getlName() == null){

                    errors.rejectValue("lName", "lName.required");
                }

                if (citizens.getDob() == null){

                    errors.rejectValue("dob", "dob.required");
                }
4

0 回答 0