SpringMVC与SiteMesh2.4无缝整合并借助JSR303规范实现表单验证
- - CSDN博客推荐文章这是个WebProject,SpringMVC用的是3.1.1,SiteMesh用的是2.4. 然后是SpringMVC的配置文件user-servlet.xml. .
这是个WebProject,SpringMVC用的是3.1.1,SiteMesh用的是2.4
首先是web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>user</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <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>
<?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/>
<%@ 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>
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