在执行Action时,输入验证时一个重要的步骤。验证范围从简单的任务到复杂的任务都有,例如简单的有检验某个输入域中是否有值,复杂的有验证信用卡号码等。
Java社区发布了 JSR 303 "Bean Validation",将Java中的输入验证标准化。
现代的MVC框架经常同时提供编程式和声明式的验证方法。
基于 MVC - 基于Filter Dispatcherr的Model2 - 示例 一节:
添加如下的Validator - ProductValidator.java
package com.gof.test.validator; import java.util.List; import java.util.ArrayList; import com.gof.test.bean.ProductForm; import com.sun.tools.javah.LLNI; public class ProductValidator { public List<String> validate(ProductForm productForm){ List<String> errors = new ArrayList<String>(); String name = productForm.getName(); if (name == null || name.trim().isEmpty()){ errors.add("Product must have a name"); } String price = productForm.getPrice(); if (price == null || price.trim().isEmpty()){ errors.add("Price must have a price"); }else{ try{ Float.parseFloat(price); }catch (NumberFormatException e){ errors.add("Invalid price value"); } } return errors; } }
修改上一个的Filter为:
package com.gof.test.filter; import java.io.IOException; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gof.test.action.SaveProductAction; import com.gof.test.bean.Product; import com.gof.test.bean.ProductForm; import com.gof.test.validator.ProductValidator; public class DispatcherFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { String uri = ((HttpServletRequest)req).getRequestURI(); int lastIndex = uri.lastIndexOf("/"); String action = uri.substring(lastIndex + 1); String dispatchUrlString = null; if (action.equals("product_input")){ dispatchUrlString = "/jsp/controller/ProductForm.jsp"; }else if (action.equals("product_save")){ ProductForm productForm = new ProductForm(); productForm.setName(req.getParameter("name")); productForm.setDescription(req.getParameter("description")); productForm.setPrice(req.getParameter("price")); // begin validate ProductValidator productValidator = new ProductValidator(); List<String> errors = productValidator.validate(productForm); // end validate if (errors.isEmpty()){ Product product = new Product(); product.setName(productForm.getName()); product.setDescription(productForm.getDescription()); product.setPrice(Float.parseFloat(productForm.getPrice())); SaveProductAction saveProductAction = new SaveProductAction(); saveProductAction.save(product); req.setAttribute("product", product); dispatchUrlString = "/jsp/controller/ProductDetails.jsp"; }else{ req.setAttribute("errors", errors); req.setAttribute("form", productForm); dispatchUrlString = "/jsp/controller/ProductForm.jsp"; } } if (dispatchUrlString != null){ RequestDispatcher rDispatcher = req.getRequestDispatcher(dispatchUrlString); rDispatcher.forward(req, resp); }else{ chain.doFilter(req, resp); } } public void destroy() { // TODO Auto-generated method stub } }
修改 ProductForm.jsp如下:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Add Product Form</title> </head> <body> <div> <h3>Add a product</h3> <c:if test="${requestScope.errors != null}"> <p> <ul> <c:forEach var="error" items="${requestScope.errors}"> <li>${error}</li> </c:forEach> </ul> </p> </c:if> <form method="post" action="product_save"> <table> <tr> <td>Product Name:</td> <td><input type="text" name="name" value="${form.name}"/></td> </tr> <tr> <td>Description:</td> <td><input type="text" name="description" value="${form.description}"/></td> </tr> <tr> <td>Price:</td> <td><input type="text" name="price" value="${form.price}"/></td> </tr> <tr> <td><input type="reset" /></td> <td><input type="submit" value="Add Product"/></td> </tr> </table> </form> </div> </body> </html>
访问如下URL:
http://localhost:8080/base-webapp/product_input
输入错误信息,提交: