首先是web.xml
java
<?xml version="1.0" encoding="UTF-8"?> web
<web-app version="2.5" spring
xmlns="http://java.sun.com/xml/ns/javaee" api
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" spring-mvc
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee mvc
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> app
<servlet> webapp
<servlet-name>user</servlet-name> jsp
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> ui
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>SpringCharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SpringCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
而後是SpringMVC的配置文件user-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jadyer"/>
<!-- 若是ClassPath中有JSR-303的實現,例如Hibernate-Validator,則支持@Valid修飾的參數 -->
<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
而後是SiteMesh的配置文件decorators.xml
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/WEB-INF/sitemesh/">
<decorator name="main" page="basic.jsp">
<pattern>/*</pattern>
</decorator>
</decorators>
接下來是SiteMesh用到的頁面//WEB-INF//sitemesh//basic.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator"%>
<h1>User Manager</h1>
<hr/>
<decorator:body/>
下面是含有表單的添加用戶信息頁面//WEB-INF//jsp//user//add.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form method="POST" modelAttribute="user">
username:<form:input path="username"/><form:errors path="username"/><br/>
nickname:<form:input path="nickname"/><form:errors path="nickname"/><br/>
password:<form:password path="password"/><form:errors path="password"/><br/>
email:<form:input path="email"/><form:errors path="email"/><br/>
<input type="submit"/>
</form:form>
下面是表單驗證經過後打印用戶信息的頁面//WEB-INF//jsp//user//list.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach items="${users}" var="user">
${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email}
<br/>
</c:forEach>
<a href="<%=request.getContextPath()%>/user/add">繼續添加新用戶</a>
接下來是使用註解處理表單驗證細節的實體類User.java
package com.jadyer.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
/**
* User
* @see ===================================================================================================
* @see JSR303是JavaEE6中的一項子規範,叫作BeanValidation,它的官方參考實現是hibernate-validator
* @see BeanValidation如今一共有兩個規範:BeanValidation1.0(即JSR303)和BeanValidation1.1(即JSR349)
* @see BeanValidation的官網是http://beanvalidation.org/
* @see 關於JSR303的詳細說明,請參考http://jcp.org/en/jsr/detail?id=303
* @see 關於JSR349的詳細說明,請參考http://jcp.org/en/jsr/detail?id=349
* @see ===================================================================================================
* @see JSR303規範主要用於對JavaBean中的字段的值的驗證,使得驗證邏輯從業務代碼中脫離出來
* @see JSR303定義了基於註解方式的JavaBean驗證元數據模型和API,也可經過XML進行元數據定義,但註解會覆蓋XML的定義
* @see JSR303主要是對JavaBean進行驗證,而沒有指定方法級別(參數or返回值)、依賴注入等驗證,所以催生了JSR349規範
* @see JSR349規範目前處於草案狀態,它主要支持依賴注入的驗證和方法級別的驗證(方法的參數和返回值)
* @see Spring3.1目前已經徹底支持依賴注入驗證和方法級別的驗證了,只不過不是原生的(JSR349規範仍是草案嘛)
* @see 關於這個的詳細說明,能夠參考此爺的文章http://www.iteye.com/topic/1123007
* @see ===================================================================================================
* @see 另外,Struts2已經能夠很完美的和JSR303整合到一塊兒了,呵呵,非常叫我欣慰啊!!!!
* @see ===================================================================================================
* @see 咱們這裏使用的是JSR303的hibernate-validator實現,它主要須要如下三個jar包
* @see jboss-logging-3.1.0.CR2.jar
* @see validation-api-1.0.0.GA.jar
* @see hibernate-validator-4.3.0.Final.jar
* @see ===================================================================================================
* @author http://blog.csdn.net/jadyer
* @create May 12, 2012 3:00:46 AM
*/
public class User {
@NotEmpty(message="姓名不能爲空")
private String username;
private String nickname;
@Size(min=3, max=10, message="密碼長度必須大於3小於10")
private String password;
@NotEmpty(message="郵箱不能爲空")
@Email(message="郵箱格式不正確") //也可經過@Pattern(regexp="")書寫正則來判斷,兩者都是JSR303規範中的
private String email;
public User() {}
public User(String username, String nickname, String password, String email) {
this.username = username;
this.nickname = nickname;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
最後是SpringMVC的控制器UserController.java
package com.jadyer.controller;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.jadyer.model.User;
/**
* @see ====================================================================================
* @see SpringMVC中藉助JSR303規範進行表單驗證
* @see 第一步:在實體類中針對須要驗證的屬性,進行Annotation配置
* @see 第二步:在Controller的方法參數前使用@Valid開啓JSR303驗證,並添加BindingResult參數
* @see BindingResult承載着JSR303驗證時所產生的message,可據此進行判斷驗證結果
* @see 第三步:判斷BindingResult中是否裝載了JSR303驗證的message,有則轉到前臺頁面顯示出來
* @see 第四步:前臺頁面中使用<form:errors path="username"/>打印JSR303的message信息
* @see ====================================================================================
* @see SpringMVC與sitemesh2.4無縫整合
* @see 第一步:拷貝sitemesh-2.4.jar到工程中
* @see 第二步:在web.xml中配置com.opensymphony.sitemesh.webapp.SiteMeshFilter
* @see 第三步:建立並編輯sitemesh配置文件decorators.xml
* @see 第四步:建立並編輯/WEB-INF/sitemesh/basic.jsp
* @see ====================================================================================
* @author http://blog.csdn.net/jadyer
* @create May 12, 2012 3:20:46 AM
*/
@Controller
@RequestMapping("/user")
public class UserController {
private final static Map<String,User> users = new HashMap<String,User>();
@RequestMapping(value="/add", method=RequestMethod.GET)
public String addUser(Model model){
model.addAttribute(new User());
return "user/add";
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public String addUser(@Valid User user, BindingResult binding){
//該方法如有其它參數,應寫成這樣addUser(@Valid User user, BindingResult binding, String job)
//就是說,這裏必定要把BindingResult放在待驗證對象(@Valid User user)參數的後面,不然會報錯
if(binding.hasErrors()){
return "user/add";
}
users.put(user.getUsername(), user);
return "redirect:/user/list";
}
@RequestMapping("/list")
public String list(Model model){
model.addAttribute("users", users);
return "user/list";
}
}
補充:本示例的訪問地址是http://127.0.0.1:8080/SpringMVC_study/user/add