0

您好,我的 jsp 页面返回空属性。每次填写表格时,我都会收到“必须填写所有字段”错误。这是我的代码:

jsp代码

 <%@ page pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Registration with eBank</title>
<link type="text/css" rel="stylesheet" href="style1.css" />
</head>
<body>
    <form method="post" action="registrationAdmin" enctype="multipart/form-data">
        <fieldset>
            <legend>Personal Information</legend>
            <p>Begin your application with this form.</p>

            <label for="firstname">First name <span class="required">*</span></label>
            <input type="text" id="firstname" name="firstname"
                value="<c:out value="${admin.firstname}"/>" size="20" maxlength="60" />
            <span class="error">${form.errors['firstname']}</span> <br /> 
            <label for="lastname">Last name <span class="required">*</span></label> <input
                type="text" id="lastname" name="lastname"
                value="<c:out value="${admin.lastname}"/>" size="20" maxlength="60" />
            <span class="error">${form.errors['lastname']}</span> <br /> 
            <label for="email">Email address <span class="required">*</span></label>
            <input type="email" id="email" name="email"
                value="<c:out value="${admin.email}"/>" size="20" maxlength="60" />
            <span class="error">${form.errors['email']}</span> <br /> 
            <label for="password">Password <span class="required">*</span></label>
            <input type="password" id="password" name="password" value=""
                size="20" maxlength="20" /> <span class="error">${form.errors['password']}</span>
            <br />
             <label for="confirmation">Confirmation of password <span class="required">*</span></label>
                <input type="password" id="confirmation" name="confirmation" value="" size="20" maxlength="20" />
                <span class="error">${form.errors['confirmation']}</span>
            <br />
            <br />
            <input type="submit" value="registration" class="sansLabel" />
                <br />

                <p class="${empty form.errors ? 'success' : 'error'}">${form.result}</p>
                <br />
        </fieldset>

    </form>

</body>
</html>

小服务程序代码:

 public class RegistrationAdmin extends HttpServlet {
        public static final String CONF_DAO_FACTORY = "daofactory";
        public static final String ATT_ADMIN = "admin";
        public static final String ATT_FORM = "form";
        public static final String VUE = "/WEB-INF/registrationAdmin.jsp";
        private AdminDao adminDao;
        public void init() throws ServletException{
            //get instance of DAO user
            this.adminDao = ((DAOFactory)getServletContext().getAttribute(CONF_DAO_FACTORY)).getAdminDao();
        }
        public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
            /* Affichage de la page d'inscription */
            this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
        }
        public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
            //String path = this.getServletConfig().getInitParameter(PATH);
            /* Préparation de l'objet formulaire */
            RegistrationAdminForm form = new RegistrationAdminForm(adminDao);

            /* Appel au traitement et à la validation de la requête, et récupération du bean en résultant */
            Admin admin = form.registerAdmin( request);

            /* Stockage du formulaire et du bean dans l'objet request */
            request.setAttribute( ATT_FORM, form );
            request.setAttribute( ATT_ADMIN, admin);

            this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
        }


    }

和我的表单代码:

public class RegistrationAdminForm {
    private static final String EMAIL_FIELD = "email";
    private static final String PASS_FIELD = "password";
    private static final String FNAME_FIELD = "firstname";
    private static final String LNAME_FIELD = "lastname";
    private static final String CONF_FIELD = "confirmation";
    private static final String ALGO = "SHA-256";
    private String result;
    private Map<String, String> errors = new HashMap<String, String>();

    public String getResult() {
        return result;
    }

    public Map<String, String> getErrors() {
        return errors;
    }
    private AdminDao adminDao;
    public RegistrationAdminForm(AdminDao adminDao){
        this.adminDao = adminDao;
    }
    public Admin registerAdmin( HttpServletRequest request ) {
        String email = getFieldValue( request, EMAIL_FIELD );
        String password = getFieldValue( request, PASS_FIELD );
        String firstname = getFieldValue( request, FNAME_FIELD );
        String lastname = getFieldValue( request, LNAME_FIELD );
        String confimation = getFieldValue( request, CONF_FIELD );
        Admin admin = new Admin();
        try{
            try {
                validateEmail( email );
            } catch (FormValidationException e ) {
                setError( EMAIL_FIELD, e.getMessage() );
            }
            admin.setEmail( email );

            try {
                validateName( firstname, lastname );
            } catch (FormValidationException e ) {
                setError( FNAME_FIELD, e.getMessage() );
                setError( LNAME_FIELD, e.getMessage() );
            }
            admin.setFirstname(firstname);
            admin.setLastname(lastname);
            treatPassword(password, confimation, admin);
            if ( errors.isEmpty() ) {

                adminDao.create(admin);
                result = "Congrats, you are successfully registred!";
            } else {
                result = "Registration failed. Please try again!";
            }
        }catch(DAOException e){
            result = "Registration Error, Please try again Later...";
            e.printStackTrace();
        }

        return admin;
    }
    private void validateName( String firstname, String lastname ) throws FormValidationException {
        if ( firstname != null && lastname !=null ) {
            if ( firstname.length() < 3 ) {
                throw new FormValidationException( "Firstname must be at least 3 characters long" );
            }else if ( lastname.length() < 3 ){
                throw new FormValidationException( "Lastname must be at least 3 characters long" );
            }
        } else {
            throw new FormValidationException( "All fields must be filled out." );
        }
    }
    private void validateEmail( String email ) throws FormValidationException {
        if ( email != null ) {
            if ( !email.matches( "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)" ) ) {
                throw new FormValidationException( "Please enter a valid email address!" );
            }else if(adminDao.find(email)!= null){
                throw new FormValidationException("This email address is already used for another account, Please choose another email address.");

            }
        }else{
                throw new FormValidationException( "Please enter an email address!" );
        }
    }
    private void treatPassword (String password, String confirmation, Admin admin){
        try {
            validatePassword( password, confirmation );
        } catch ( FormValidationException e ) {
            setError( PASS_FIELD, e.getMessage() );
            setError( CONF_FIELD, null );
        }
        ConfigurablePasswordEncryptor passwordEncryptor = new ConfigurablePasswordEncryptor();
        passwordEncryptor.setAlgorithm( ALGO );
        passwordEncryptor.setPlainDigest( false );
        String encyptedPassword = passwordEncryptor.encryptPassword( password );

        admin.setPassword(encyptedPassword);
    }
    private void validatePassword( String password, String confirmation ) throws FormValidationException {
        if ( password != null && confirmation != null ) {
            if ( !password.equals( confirmation ) ) {
                throw new FormValidationException( "Passwords don't match!" );
            } else if ( password.length() < 6 ) {
                throw new FormValidationException( "Passwords must be at least 6 characters long" );
            }
        } else {
            throw new FormValidationException( "Please enter and confirm your password!" );
        }
    }
    private void setError( String field, String message ) {
        errors.put( field, message );
    }


     private static String getFieldValue( HttpServletRequest request, String FieldName ) {
            String value = request.getParameter( FieldName );
            if ( value == null || value.trim().length() == 0 ) {
                return null;
            } else {
                return value;
            }
     }
}

尽管参数名称与 JSP 中的名称匹配,但 request.getParamaeter("param") 每次都返回 null。任何帮助将不胜感激。谢谢

4

1 回答 1

0

您应该删除:

enctype="multipart/form-data"

request.getParameter() 不适用于多部分表单。

于 2017-05-19T13:41:55.073 回答