SpringMVC 专题
您的位置:java > SpringMVC专题 > Spring MVC错误处理
Spring MVC错误处理
作者:--    发布时间:2019-11-19

以下示例显示如何在使用spring web mvc框架的表单中使用错误处理和验证器。首先使用eclipse ide来创建一个web工程,实现一个输入用户信息提交验证提示的功能。并按照以下步骤使用spring web framework开发基于动态表单的web应用程序:

  1. 创建一个名称为 errorhandling 的动态web项目。
  2. com.h3.springmvc 包下创建三个java类studentstudentcontrollerstudentvalidator
  3. jsp子文件夹下创建两个视图文件:addstudent.jspresult.jsp
  4. 最后一步是创建所有源和配置文件的内容并运行应用程序,详细如下所述。

完整的项目文件目录结构如下所示 -

student.java 的代码如下所示 -

package com.h3.springmvc;

public class student {
   private integer age;
   private string name;
   private integer id;

   public void setage(integer age) {
      this.age = age;
   }
   public integer getage() {
      return age;
   }

   public void setname(string name) {
      this.name = name;
   }
   public string getname() {
      return name;
   }

   public void setid(integer id) {
      this.id = id;
   }
   public integer getid() {
      return id;
   }
}

studentvalidator.java 的代码如下所示 -

package com.h3.springmvc;

import org.springframework.validation.errors;
import org.springframework.validation.validationutils;
import org.springframework.validation.validator;

public class studentvalidator implements validator {

   @override
   public boolean supports(class<?> clazz) {
      return student.class.isassignablefrom(clazz);
   }

   @override
   public void validate(object target, errors errors) {        
      validationutils.rejectifemptyorwhitespace(errors, 
         "name", "required.name","field name is required.");
   }
}

studentcontroller.java 的代码如下所示 -

package com.h3.springmvc;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.validation.bindingresult;
import org.springframework.validation.validator;
import org.springframework.validation.annotation.validated;
import org.springframework.web.bind.webdatabinder;
import org.springframework.web.bind.annotation.initbinder;
import org.springframework.web.bind.annotation.modelattribute;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.servlet.modelandview;

@controller
public class studentcontroller {

   @autowired
   @qualifier("studentvalidator")
   private validator validator;

   @initbinder
   private void initbinder(webdatabinder binder) {
      binder.setvalidator(validator);
   }

   @requestmapping(value = "/addstudent", method = requestmethod.get)
   public modelandview student() {
      return new modelandview("addstudent", "command", new student());
   }

   @modelattribute("student")
   public student createstudentmodel() {    
      return new student();
   }

   @requestmapping(value = "/addstudent", method = requestmethod.post)
   public string addstudent(@modelattribute("student") @validated student student, 
      bindingresult bindingresult, model model) {

      if (bindingresult.haserrors()) {
         return "addstudent";
      }
      model.addattribute("name", student.getname());
      model.addattribute("age", student.getage());
      model.addattribute("id", student.getid());

      return "result";
   }
}

这里的第一个服务方法student(),我们已经在modelandview对象中传递了一个名称为“command”的空student对象,因为如果在jsp文件中使用<form:form>标签,spring框架需要一个名称为“command”的对象。 所以当调用student()方法时,它返回student.jsp视图。

第二个服务方法addstudent()将根据url => errorhandling/addstudent 上的post方法请求时调用。根据提交的信息准备模型对象。 最后从服务方法返回“result”视图,这将呈现result.jsp视图。

addstudent.jsp 的代码如下所示 -

<%@ page contenttype="text/html; charset=utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>spring mvc表单错误处理</title>
</head>
<style>
.error {
    color: #ff0000;
}

.errorstyle {
    color: #000;
    background-color: #ffeeee;
    border: 3px solid #ff0000;
    padding: 8px;
    margin: 16px;
}
</style>
<body>

    <h2>学生信息</h2>
    <form:form method="post" action="/errorhandling/addstudent"
        commandname="student">
        <form:errors path="*" cssclass="errorstyle" element="div" />
        <table>
            <tr>
                <td><form:label path="name">姓名:</form:label></td>
                <td><form:input path="name" /></td>
                <td><form:errors path="name" cssclass="error" /></td>
            </tr>
            <tr>
                <td><form:label path="age">年龄:</form:label></td>
                <td><form:input path="age" /></td>
            </tr>
            <tr>
                <td><form:label path="id">编号:</form:label></td>
                <td><form:input path="id" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交" /></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

这里使用<form:errors />标签来呈现html隐藏字段域。 例如 -

<form:errors path="*" cssclass="errorblock" element="div" />

它将呈现所有输入验证的错误消息。
使用带有path =“name”<form:errors />标记来渲染name字段的错误消息。

<form:errors path="name" cssclass="error" />

它将呈现名称字段验证的错误消息。

result.jsp 的代码如下所示 -

<%@ page contenttype="text/html; charset=utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>spring mvc表单错误处理</title>
</head>
<body>

<h2>submitted student information</h2>
   <table>
    <tr>
        <td>姓名:</td>
        <td>${name}</td>
    </tr>
    <tr>
        <td>年龄:</td>
        <td>${age}</td>
    </tr>
    <tr>
        <td>编号:</td>
        <td>${id}</td>
    </tr>
</table>  
</body>
</html>

完成创建源和配置文件后,发布应用程序到tomcat服务器。

现在启动tomcat服务器,现在尝试访问url => http://localhost:8080/errorhandling/addstudent ,如果spring web应用程序没有问题,应该看到以下结果:

提交所需信息后,点击提交按钮提交表单。 如果 spring web 应用程序没有问题,应该看到以下结果:


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册