首页 > 其他分享 >spring3 mvc 效验例子

spring3 mvc 效验例子

时间:2023-05-08 15:31:44浏览次数:43  
标签:validationForm under Step mvc 效验 import spring3 validation public


The application will present simple user registration form to the user. Form will have the following fields:
1. User Name
2. Age
3. Password
The validator framework will validate the user input. If there is any validation error application will display the appropriate message on the form.
To use the validation framework in the application "hibernate-validator-4.0.2.GA.jar" and " validation-api-1.0.0.GA.jar" must be added to the project libraries.
Application uses following jar files:





Step 1:


Create index.jsp  under WebContent . The code index.jsp as :



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Spring 3, MVC Examples</title>
</head>
<body>
<h1>Spring 3, MVC Examples</h1>
<ul>
<li><a href="forms/validationform.html">Validation Form</a></li>
</ul>
</body>
</html>

In the above page we are creating a new link to access the Validation Form example from the index page of the application.

Step 2:

Now  we will create a  model class " ValidationForm.java"  under src folder . The code of   "ValidationForm.java" is:

package net.roseindia.form;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;

public class ValidationForm {
        @NotEmpty
        @Size(min = 1, max = 20)
        private String userName;
        @NotNull
        @NumberFormat(style = Style.NUMBER)
        @Min(1)
        @Max(110)
        private Integer age;
        @NotEmpty(message = "Password must not be blank.")
        @Size(min = 1, max = 10, message = "Password must between 1 to 10 Characters.")
        private String password;

        public void setUserName(String userName) {
                this.userName = userName;
        }

        public String getUserName() {
                return userName;
        }

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

        public Integer getAge() {
                return age;
        }

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

        public String getPassword() {
                return password;
        }
}

In the above class we have added the proper annotation for validating the form values. Here is the list of annotation used for validation:

@NotEmpty
@Size(min = 1, max = 20)
@NotNull
@NumberFormat(style = Style.NUMBER)
@Min(1)
@Max(110)
@NotEmpty(message = "Password must not be blank.")
@Size(min = 1, max = 10, message = "Password must between 1 to 10 Characters.")

Step 3 :

Now create a folder views under WebContent/WEB-INF . Again  cerate "validationform.jsp"  under WebContent/WEB-INF/views as :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="post" action="validationform.html"

commandName="validationForm">
<table>
<tr>
<td>User Name:<font color="red"><form:errors
path="userName" /></font></td>
</tr>
<tr>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td>Age:<font color="red"><form:errors path="age" /></font></td>
</tr>
<tr>
<td><form:input path="age" /></td>
</tr>
<tr>
<td>Password:<font color="red"><form:errors
path="password" /></font></td>
</tr>
<tr>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

In this above jsp file <form:errors path="..." />  tag is used to display the validation error messages.

Step 4:

Now  create "validationsuccess.jsp" file under  WebContent/WEB-INF/views . The code of  "validationsuccess.jsp"  is :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>
<%@taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<core:out value="${validationForm.userName}" /> Save Successfully.
</body>
</html>

Step 5:

Now create  Contoller class "ValidationController.java" under src folder.  Controller class use for  RequestMapping  and process the user request. The  code of   "ValidationController.java"   as:

package net.roseindia.controllers;

import net.roseindia.form.ValidationForm;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/validationform.html")
public class ValidationController {

        // Display the form on the get request
        @RequestMapping(method = RequestMethod.GET)
        public String showValidatinForm(Map model) {
                ValidationForm validationForm = new ValidationForm();
                model.put("validationForm", validationForm);
                return "validationform";
        }

        // Process the form.
        @RequestMapping(method = RequestMethod.POST)
        public String processValidatinForm(@Valid ValidationForm validationForm,
                        BindingResult result, Map model) {
                if (result.hasErrors()) {
                        return "validationform";
                }
                // Add the saved validationForm to the model
                model.put("validationForm", validationForm);
                return "validationsuccess";
        }

}

The @RequestMapping annotation is used for request uri mapping.

Step 6:

Now modify web.xml as:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">

 
<display-name>Spring3Example</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Step 7:

Again create "dispatcher-servlet.xml"  under  WebContent/WEB-INF . The "dispatcher-servlet.xml"  code as :

<?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:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

">

 
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />

 
<context:component-scan base-package="net.roseindia.controllers"/>

 
<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

 
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

 
<bean id="messageSource"class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>

 
</beans>


Where <mvc:annotation-driven> is used for annotation driven controllers and validation. While message Resource configuration is done in "dispatcher-servlet.xml" using following entry:

<bean id="messageSource"class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>

Again  create customization  Message file  "messages.properties"  under  WebContent/WEB-INF. The modify  "messages.properties"  as

NotEmpty.validationForm.userName=User Name must not be blank.

Size.validationForm.userName=User Name must between 1 to 20 characters.

Step 8:

Now run Application display output as :

if click  Validation Form  hyperlink then open validationform as :

Step 9:

Now Enter  userName,  Age and Password if find any error display as:

  

Again display  error-

If validation  success then display validationsucess page as :

标签:validationForm,under,Step,mvc,效验,import,spring3,validation,public
From: https://blog.51cto.com/u_16087105/6254545

相关文章

  • java--Servlet以及Mvc的实现
    ServletServlet的生命周期Servlet的生命周期可以分为四个步骤:实例化。当Web容器(如Tomcat)启动时,会首先加载Servlet类,并创建Servlet实例。这一过程通常在应用程序启动时完成。初始化。接着容器会调用Servlet实例的init()方法来进行初始化操作。在这个方法中,通......
  • AspNetCoreRateLimit应用于MVC项目求助
    AspNetCoreRateLimit应用于MVC项目求助前言之前发过一篇文章:.NETCoreWebApi接口ip限流实践-妙妙屋(zy)-博客园(cnblogs.com)然后应用在前后端分离项目这个组件是非常好用的。但应用于不分离的项目,比如我的个人博客就有点麻烦。就是我的需求是评论接口限流,然后触发限流后......
  • ASP.NET Core MVC 从入门到精通之序列化
    随着技术的发展,ASP.NETCoreMVC也推出了好长时间,经过不断的版本更新迭代,已经越来越完善,本系列文章主要讲解ASP.NETCoreMVC开发B/S系统过程中所涉及到的相关内容,适用于初学者,在校毕业生,或其他想从事ASP.NETCoreMVC系统开发的人员。经过前几篇文章的讲解,初步了解ASP.NETCore......
  • springmvc知识梳理 一篇就能让你的项目按照springmvc框架跑起来
    springmvc目录1.创建基本框架步骤2.@RequestMapping()2.1value属性2.1.1路径支持ant风格2.1.2restful风格2.2method属性2.2.1form表单问题:2.2.2get和post相关问题(涉及面试题):2.3param属性书写格式:thymeleaf语法:2.4headers属性3.获取请求参数......
  • SpringMvc
    SpringMVC1SpringMVC概述问题导入SpringMVC框架有什么优点?1.1SpringMVC概述SpringMVC是一种基于Java实现MVC模型的轻量级Web框架优点使用简单,开发便捷(相比于Servlet)灵活性强2入门案例【重点】问题导入在Controller中如何定义访问路径,如何响应数据?2.1实现步骤......
  • 使用IDEA2023创建springMVC项目,web项目
    1.使用idea2022创建web项目 2.新建模块 3.编写文件名,记住如果想单独一个项目,不想被包括在其他项目里面就取消位置后面的地址,它有可能是上一个项目的主文件 4.创建完主要项目以后要添加web模块,先选中需要添加web项目的模块,再店家上方+号,选择 web模块 3.修改部......
  • spring mvc 报406错误
    我也不知道真正的原因是什么,可能是返回的格式不正确吧,猜测而已,因为之前返回的是Map,这样不行,改为返回字符串String就可以了.原因是缺少jar包,详见http://jadethao.iteye.com/blog/1926525http://macrotea.iteye.com/blog/1179509......
  • IDEA导入SpringMvc文件-Tomcat部署web的文件
                    ......
  • Spring MVC 单元测试
    关键字:SpringMVC单元测试下面一步一步带领大家实现springMVC单元测试:新建一个基类:packagetest;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.junit.BeforeClass;importo......
  • spring3.0 mvc和rest入门例子
    关键字:spring3.0mvc和rest入门例子现在写个简单的小例子出来给初学者学习下。srping3也支持rest,所以例子也包括这部分内容。先看web.xml配置<!--像js,css,gif等静态文件,需要配置为默认的servlet--><servlet-mapping><servlet-name>defaul......