如何避免Spring MVC中的特殊字符

时间:2017-01-31 08:05:40

标签: spring

您正在对表单字段进行服务器端验证,请参阅正确获取所有错误消息,但如何避免使用%#$ ^& *对于每个输入字段以及当我收到错误消息时如何使输入框边框变为红色

为了避免使用特殊字符,我必须使用ESAPI.validator()。getValidInput 如何使用下面的try catch代码在验证器类中避免使用特殊字符

    try
    {
ESAPI.validator().getValidInput("Validationofmobilenumber", mobilenumber, "Onlynumber", 200, false);
            ESAPI.validator().getValidInput("Validationofinput", Studentname, "Onlycharacters", 200, false);
    }
    catch (ValidationException e) {
                ESAPI.log().error(Logger.EVENT_FAILURE, e.getMessage());
                System.out.println("in validation");
                addActionError("Do not enter special character like % # $ ^ & *...... ");

            } catch (IntrusionException ie) {
                ESAPI.log().error(Logger.EVENT_FAILURE, ie.getMessage());
    addActionError("Do not enter special character like % # $ ^ & *...... ");

            } catch (Exception e) {
                System.out.println(e);

            }

控制器

@Controller
public class RegistrationController {

    @Autowired
    CustomerValidator customerValidator;



     @RequestMapping(value = "/register", method = RequestMethod.GET)
        public String viewRegistrationPage(Model model) {
          Customer customer = new Customer();
            model.addAttribute("customer", customer);
            return "register";
        }

     @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
        public String doLogin(@Valid Customer customer, BindingResult result,Model model) {
         model.addAttribute("customer",customer);
         customerValidator.validate(customer, result);
          if(result.hasErrors()){
              return "register";
          }

          return "home";
        }

    public CustomerValidator getCustomerValidator() {
        return customerValidator;
    }

    public void setCustomerValidator(CustomerValidator customerValidator) {
        this.customerValidator = customerValidator;
    }

}

模型 公共类客户{

@NotEmpty   
    @Email
    private String emailId;

    @Size(min=8,max=15)
    private String password;


    @Size(min=8,max=15)
    private String confPassword;

    private int age;

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getPassword() {
        return password;
    }

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

    public String getConfPassword() {
        return confPassword;
    }

    public void setConfPassword(String confPassword) {
        this.confPassword = confPassword;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

验证

@Component
public class CustomerValidator implements Validator {

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

    public void validate(Object target, Errors errors) {
        Customer customer = (Customer)target;
        int age = customer.getAge();
        String password = customer.getPassword();
        String confPassword = customer.getConfPassword();


        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "customer.age.empty");



        //Business validation
        if(!password.equals(confPassword)){
            errors.rejectValue("password","customer.password.missMatch");
        }


        if(age < 18 || age > 60){
            errors.rejectValue("age", "customer.age.range.invalid");
        }       
    }
}

JSP         

        <tr>
            <td>Enter your E-mail:</td>
            <td><form:input path="emailId" /></td>
            <td><form:errors path="emailId" cssStyle="color: #ff0000;" /></td>
        </tr>

        <tr>
            <td>Enter your Age:</td>
            <td><form:input path="age"/></td>
            <td><form:errors path="age" cssStyle="color: #ff0000;"/></td>
        </tr>

        <tr>
            <td>Enter your password:</td>
            <td><form:password path="password"  showPassword="true"/></td>
            <td><form:errors path="password" cssStyle="color: #ff0000;"/></td>
        </tr>

            <tr>
            <td>Confirm your password:</td>
            <td><form:password path="confPassword"  showPassword="true"/></td>
            <td><form:errors path="confPassword" cssStyle="color: #ff0000;"/></td>
        </tr>

        <tr>
            <td><input type="submit" name="submit" value="Click here to Register"></td>
        </tr>
    </table>
</form:form>

属性

NotEmpty.customer.emailId=Email Id is required. 
Email.customer.emailId=valid email id is required.
Size.customer.password=Password should be minimum of 8 and maximum of 15 characters.
Size.customer.confPassword=Password should be minimum of 8 and maximum of 15 characters.
customer.age.empty = Age is required
customer.age.range.invalid = Age should be between 18 to 60
customer.password.missMatch = password and confirm password do not match

2 个答案:

答案 0 :(得分:1)

对于验证使用@Pattern注释,如下所示:

    @Pattern(regexp = "^[a-zA-Z0-9.\\-\\/+=@_ ]*$")
    @NotEmpty   
    @Email
    private String emailId;

对于错误字段红色边框,为错误添加一个css类,并为该类放置css样式,并将其放在jsp的head块或者你拥有的css文件中。

    <tr>
        <td>Enter your E-mail:</td>
        <td><form:input path="emailId" /></td>
        <td><form:errors path="emailId" cssClass="error" /></td>
    </tr>

    <style>
        .error {
            color: red;
            border: 1px solid red;
        }
    </style>

如果要使用ESAPI验证程序,请在ESAPI.properties中添加此规则

Validator.ValidInput=^[a-zA-Z0-9.\\-\\/+=@_ ]*$

然后为Validator类中的每个输入添加以下内容,例如我只给出一个。

        try {
            if (!ESAPI.validator().isValidInput("ValidationOfPassword", password, "ValidInput", 200, false)) {
                errors.rejectValue("password","customer.password.missMatch");//replace your msg property in second param
            }
        } catch (Exception e) {
            //something gone wrong
            e.printStackTrace();
            errors.rejectValue("password","customer.password.missMatch");//replace your msg property in second param
        }

答案 1 :(得分:0)

在您的字段上,您可以使用javax.validation.constraints.Pattern注释,然后使用&#34; [\ w] *&#34;这意味着只有字母数字字符。