欢迎访问 生活随笔!

尊龙游戏旗舰厅官网

当前位置: 尊龙游戏旗舰厅官网 > 前端技术 > javascript >内容正文

javascript

spring4 mvc表单验证代码示例 -尊龙游戏旗舰厅官网

发布时间:2025/1/21 javascript 16 豆豆
尊龙游戏旗舰厅官网 收集整理的这篇文章主要介绍了 spring4 mvc表单验证代码示例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

在这篇文章中,我们将学习如何使用spring表单标签, 表单验证使用 jsr303 的验证注解,hibernate-validators,提供了使用messagesource和访问静态资源(如css,javascript,图片)国际化支持我们的视图,使用resourcehandlerregistry,全部采用基于注解的配置。

我们将创建一个包含一个学生注册表格的简单应用,用户输入表单提交验证通过 jsr303 的验证注释验证,通过覆盖属性文件可使用国际验证消息的默认消息,还访问静态资源(如应用引导css到网页中)。

请注意,jsr303是一种规范,hibernate-validator是我们在这篇文章中使用的一种实现,它也提供了几个不包含在规范中自己的验证注释。

使用以下技术:

  • spring 4.0.6.release
  • validation-api 1.1.0.final
  • hibernate-validator 5.1.2.final
  • bootstrap v3.1.0
  • maven 3
  • jdk 1.6
  • tomcat 7.0.54
  • eclipse juno service release 2

我们现在开始!

第1步:创建目录结构

以下将是最终的项目结构(这里需要先创建一个maven工程为:spring4mvcformvalidationexample):

 

现在让我们在每个细节上述结构中提到的内容来做一点解释。

第2步:更新pom.xml,包括所需的依赖关系

4.0.0com.yiibai.springmvcspring4mvcformvalidationexamplewar1.0.0spring4mvcformvalidationexample4.0.6.release5.1.2.final1.1.0.finalorg.springframeworkspring-core${springframework.version}org.springframeworkspring-web${springframework.version}org.springframeworkspring-webmvc${springframework.version}javax.validationvalidation-api${javax.validation.version}org.hibernatehibernate-validator${hibernate.validator.version}javax.servletjavax.servlet-api3.1.0javax.servlet.jspjavax.servlet.jsp-api2.3.1javax.servletjstl1.2org.apache.maven.pluginsmaven-war-plugin2.4src/main/webappspring4mvcformvalidationexamplefalsespring4mvcformvalidationexample

首先要注意这里是 maven-war-plugin 插件声明。由于我们使用的是全注解配置,我们甚至不包括在 web.xml 中,所以我们需要配置这个插件,以避免maven构建war包失败。在验证部分 validation-api 代表规范, 而hibernate-validator是本规范的一个实现。hibernate-validator还提供了一些它自己的注解(@email,@notempty等)不属于规范的一部分。

伴随着这一点,我们也包括jsp/servlet/jstl 的依赖关系,也将需要为使用 servlet api和jstl视图在我们的代码中。在一般情况下,容器可能已经包含了这些库,从而在pom.xml中我们可以设置范围作为“provided”。

此外,这里还单独下载了 bootstrap.css ,为了演示在基于注解的配置如何使用资源处理。

第3步:创建pojo/域对象

访问的对象将充当一个辅助bean的形式保存用户提供签证申请表提交的数据。我们将注释,以验证属性(使用验证注释)。

com.yiibai.springmvc.model.student

package com.yiibai.springmvc.model;import java.io.serializable; import java.util.arraylist; import java.util.date; import java.util.list;import javax.validation.constraints.notnull; import javax.validation.constraints.past; import javax.validation.constraints.size;import org.hibernate.validator.constraints.email; import org.hibernate.validator.constraints.notempty; import org.springframework.format.annotation.datetimeformat;public class student implements serializable {@size(min=3, max=30)private string firstname;@size(min=3, max=30)private string lastname;@notemptyprivate string sex;@datetimeformat(pattern="yyyy-mm-dd")@past @notnullprivate date dob;@email @notemptyprivate string email;@notemptyprivate string section;@notemptyprivate string country;private boolean firstattempt;@notemptyprivate list subjects = new arraylist();public string getfirstname() {return firstname;}public void setfirstname(string firstname) {this.firstname = firstname;}public string getlastname() {return lastname;}public void setlastname(string lastname) {this.lastname = lastname;}public string getsex() {return sex;}public void setsex(string sex) {this.sex = sex;}public date getdob() {return dob;}public void setdob(date dob) {this.dob = dob;}public string getemail() {return email;}public void setemail(string email) {this.email = email;}public string getsection() {return section;}public void setsection(string section) {this.section = section;}public string getcountry() {return country;}public void setcountry(string country) {this.country = country;}public boolean isfirstattempt() {return firstattempt;}public void setfirstattempt(boolean firstattempt) {this.firstattempt = firstattempt;}public list getsubjects() {return subjects;}public void setsubjects(list subjects) {this.subjects = subjects;}@overridepublic string tostring() {return "student [firstname=" firstname ", lastname=" lastname ", sex=" sex ", dob=" dob ", email=" email ", section=" section ", country=" country ", firstattempt=" firstattempt ", subjects=" subjects "]";}}

在上面的代码中:@size, @past & @notnull 是标准的标注,而@notempty&@emailare是规范的一部分。

第4步:添加控制器

控制器加入将有助于处理get和post请求。

com.yiibai.springmvc.controller.helloworldcontroller

package com.yiibai.springmvc.controller;import java.util.arraylist; import java.util.list;import javax.validation.valid;import org.springframework.stereotype.controller; import org.springframework.ui.modelmap; import org.springframework.validation.bindingresult; import org.springframework.web.bind.annotation.modelattribute; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod;import com.websystique.springmvc.model.student;@controller @requestmapping("/") public class helloworldcontroller {/** this method will serve as default get handler.**/@requestmapping(method = requestmethod.get)public string newregistration(modelmap model) {student student = new student();model.addattribute("student", student);return "enroll";}/** this method will be called on form submission, handling post request* it also validates the user input*/@requestmapping(method = requestmethod.post)public string saveregistration(@valid student student, bindingresult result, modelmap model){if(result.haserrors()) {return "enroll";}model.addattribute("success", "dear " student.getfirstname() " , your registration completed successfully");return "success";}/** method used to populate the section list in view.* note that here you can call external systems to provide real data.*/@modelattribute("sections")public list initializesections() {list sections = new arraylist();sections.add("graduate");sections.add("post graduate");sections.add("research");return sections;}/** method used to populate the country list in view.* note that here you can call external systems to provide real data.*/@modelattribute("countries")public list initializecountries() {list countries = new arraylist();countries.add("usa");countries.add("china");countries.add("france");countries.add("germany");countries.add("italy");countries.add("other");return countries;}/** method used to populate the subjects list in view.* note that here you can call external systems to provide real data.*/@modelattribute("subjects")public list initializesubjects() {list subjects = new arraylist();subjects.add("physics");subjects.add("chemistry");subjects.add("life science");subjects.add("political science");subjects.add("computer science");subjects.add("mathmatics");return subjects;}}  

@controller表明这个类是一个控制器在处理具有模式映射的@requestmapping请求。这里使用 ‘/’, 它被作为默认的控制器。方法newregistration是相当简单的,注解为@ requestmethod.get服务默认是get请求,使用模型对象,以服务为形式的数据,并呈现包含空白表单的网页。

方法initializesections, initializecountries & initializesubjects是简单地创建请求级别的对象,其值在视图/jsp中将被使用。

方法saveregistration 标注有@ requestmethod.post,并将处理表单提交post请求。注意本方法的参数和它们的顺序。

@valid要求spring来验证相关的对象(学生)。 bindingresult包含此验证,并可能在此验证过程中发生(产生)任何错误的结果。请注意,bindingresult一定要在之后立即生效对象,否则spring将无法验证并且将一个异常抛出。

注意,在校验失败后,默认/广义错误消息显示在屏幕上这可能不是所期望的。相反,可以重写此行为提供具体到每个字段中国际化消息。为了做到这一点,我们需要配置 messagesource 在应用程序配置类,并提供包含我们下一步将配置实际的信息属性文件。

第5步:添加配置类

com.yiibai.springmvc.configuration.helloworldconfiguration

package com.yiibai.springmvc.configuration;import org.springframework.context.messagesource; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configuration; import org.springframework.context.support.resourcebundlemessagesource; import org.springframework.web.servlet.viewresolver; import org.springframework.web.servlet.config.annotation.enablewebmvc; import org.springframework.web.servlet.config.annotation.resourcehandlerregistry; import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; import org.springframework.web.servlet.view.internalresourceviewresolver; import org.springframework.web.servlet.view.jstlview;@configuration @enablewebmvc @componentscan(basepackages = "com.yiibai.springmvc") public class helloworldconfiguration extends webmvcconfigureradapter {/** configure view resolver*/@beanpublic viewresolver viewresolver() {internalresourceviewresolver viewresolver = new internalresourceviewresolver();viewresolver.setviewclass(jstlview.class);viewresolver.setprefix("/web-inf/views/");viewresolver.setsuffix(".jsp");return viewresolver;}/** configure resourcehandlers to serve static resources like css/ javascript etc...**/@overridepublic void addresourcehandlers(resourcehandlerregistry registry) {registry.addresourcehandler("/static/**").addresourcelocations("/static/");}/** configure messagesource to provide internationalized messages**/@beanpublic messagesource messagesource() {resourcebundlemessagesource messagesource = new resourcebundlemessagesource();messagesource.setbasename("messages");return messagesource;}} 

@configuration指示该类包含注解为@bean生产bean管理是由spring容器的一个或多个 bean 的方法。@enablewebmvc 等效于 mvc:annotation-driven 在xml文件中。它能够为使用@requestmapping 向特定的方法传入的请求映射@controller-annotated类。 @componentscan 等效于  context:component-scan base-package="..." 提供具有到哪里查找管理spring beans/类。

方法 viewresolver 配置一个 viewresolver 用来找出真正的视图。方法 addresourcehandlers 配置 resourcehandler 静态资源。css, javascript, images 等都是静态的资源在你的页面里。上面的配置表示,所有的资源请求开始/static/,将从webapps文件夹下提供/static/。在这个例子中,我们把所有的css文件放在 web应用程序的 /static/css 目录中。注意,此方法在 webmvcconfigureradapter 中定义,因此我们需要扩展这个类来注册我们的静态资源覆盖此方法。

方法为 messagesource 配置消息包,以支持[国际化]消息属性文件。请注意方法 basename 提供的参数(消息)。spring 将搜索应用程序类路径中一个名为messages.properties文件。让我们添加的文件:

src/main/resources/messages.properties

size.student.firstname=first name must be between {2} and {1} characters long size.student.lastname=last name must be between {2} and {1} characters long notempty.student.sex=please specify your gender notnull.student.dob=date of birth can not be blank past.student.dob=date of birth must be in the past email.student.email=please provide a valid email address notempty.student.email=email can not be blank notempty.student.country=please select your country notempty.student.section=please select your section notempty.student.subjects=please select at least one subject typemismatch=invalid format

请注意,上述消息按照特定的模式

{validationannotationclass}.{modelobject}.{fieldname} 

此外,根据具体的注释(如@size),也可以用传递参数给这些消息:{0},{1},..{i}

以xml格式上述结构将是

messages/web-inf/views/.jsp

第6步:添加视图(简单的jsp页面)

我们将添加两个简单的jsp页面。第一个将包含一个表单,从用户接收输入, 而第二个在当表单输入验证成功时会显示成功消息给用户。

下面是代码,用于包括静态资源(在我们的例子中使用 bootstrap.css)

 

注意静态资源路径。既然我们已经在前面的步骤配置资源处理程序 /static/**, css文件将搜索 /static/文件夹。

完整的jsp文件如下所示:

web-inf/views/enroll.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8"pageencoding="utf-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> student enrollment form
male female
select country
web-inf/views/success.jsp<%@ page language="java" contenttype="text/html; charset=iso-8859-1"pageencoding="iso-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> student enrollment detail confirmation
confirmation message : ${success}
we have also sent you a confirmation mail to your email address : ${student.email}.

第7步:添加初始化器类

com.yiibai.springmvc.configuration.helloworldinitializer

package com.yiibai.springmvc.configuration;import javax.servlet.servletcontext; import javax.servlet.servletexception; import javax.servlet.servletregistration;import org.springframework.web.webapplicationinitializer; import org.springframework.web.context.support.annotationconfigwebapplicationcontext; import org.springframework.web.servlet.dispatcherservlet;public class helloworldinitializer implements webapplicationinitializer {public void onstartup(servletcontext container) throws servletexception {annotationconfigwebapplicationcontext ctx = new annotationconfigwebapplicationcontext();ctx.register(helloworldconfiguration.class);ctx.setservletcontext(container);servletregistration.dynamic servlet = container.addservlet("dispatcher", new dispatcherservlet(ctx));servlet.setloadonstartup(1);servlet.addmapping("/");}} 

内容上面类似之前教程的 web.xml 文件内容,因为我们使用的是前端控制器的dispatcherservlet,分配映射(url模式的xml)和而不是提供给spring配置文件(spring-servlet.xml)的路径,在这里,我们使用注册配置类。

更新:请注意,上面的类可以写成更加简洁[和这是最佳方法],通过扩展 abstractannotationconfigdispatcherservletinitializer 基类,如下所示:

package com.websystique.springmvc.configuration;import org.springframework.web.servlet.support.abstractannotationconfigdispatcherservletinitializer;public class helloworldinitializer extends abstractannotationconfigdispatcherservletinitializer {@overrideprotected class[] getrootconfigclasses() {return new class[] { helloworldconfiguration.class };}@overrideprotected class[] getservletconfigclasses() {return null;}@overrideprotected string[] getservletmappings() {return new string[] { "/" };}}

第8步:构建和部署应用程序

有一点要记住,如:webapplicationinitializer,spring 基于java 配置api是依赖servlet3.0容器的。所以一定要确保你没有使用 servlet 声明任何在 web.xml 小于3.0。对于我们的情况,我们要从应用程序中删除 web.xml 文件。

现在构建war 或通过maven 命令行(mvn clean install)。 部署 war 到servlet3.0容器。

运行应用程序,访问url:http://localhost:8080/spring4mvcformvalidationexample

得到的初始页面如下图所示:

 

现在,如果你提交,会得到验证错误(在 message.properties 中用户定义的消息)

 

现在提供示例输入

 

现在提交表单,结果如下:

 

到这里,完成!
代码下载:http://pan.baidu.com/s/1nukn6hv

原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/spring_mvc/spring-4-mvc-form-validation.html
 

总结

以上是尊龙游戏旗舰厅官网为你收集整理的spring4 mvc表单验证代码示例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得尊龙游戏旗舰厅官网网站内容还不错,欢迎将尊龙游戏旗舰厅官网推荐给好友。

网站地图