Spring MVC基础之错误处理

Spring MVC基础之错误处理

续:Spring MVC基础之表单标签库
1、表单标签库

8、错误处理
9、文件上传
使用IDEA创建Spring MVC项目如下:

在这里插入图片描述

代码:

dispatcher-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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--scanner for packages-->
    <context:component-scan base-package="my.controller"/>

    <!--映射到动态页面-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="student" class="my.model.Student"/>
    <bean id="studentValidator" class="my.validator.StudentValidator"/>
</beans>

StudentValidator.java(校验器)

package my.validator;
import my.model.Student;
import org.springframework.stereotype.Repository;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Repository("studentValidator")
public class StudentValidator implements Validator {
    //该校验器能够对clazz类型的对象进行校验
    @Override
    public boolean supports(Class<?> clazz) {
        //Student指定的class参数所表示的类或接口是否相同,或是否是其超类的超接口
        return Student.class.isAssignableFrom(clazz);
    }
    //对目标类target进行校验,并将校验错误记录在errors中
    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "name", null,"登录名不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", null,"密码不能为空");
        Student student = (Student) target;
        if(student.getName().length() > 10){
            //使用Errors的rejectValue方法验证
            errors.rejectValue("name", null, "用户名不能超过10个字符");
        }
        if(student.getPassword() != null && !student.getPassword().equals("") && student.getPassword().length() <6){
            errors.rejectValue("password", null, "密码不能小于6位");
        }
    }
}

StudentController.java

package my.controller;
import my.model.Student;
import my.validator.StudentValidator;
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.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class StudentController {
    @Autowired
    @Qualifier("student")
    private Student student;
    @Autowired
    @Qualifier("studentValidator")
    private StudentValidator studentValidator;

    @RequestMapping(value="/index.do",method=RequestMethod.GET)
    public String index(Model model){
        model.addAttribute("student",student);
        return "index";
    }

    @InitBinder
    public void InitBinder(DataBinder binder){
        // 设置验证的类为StudentValidator
        binder.setValidator(studentValidator);
    }

    @RequestMapping(value="/result.do",method=RequestMethod.POST)
    public String register(@Validated Student student, Errors errors){
        if (errors.hasFieldErrors()){
            return "index";
        }else{
            return "pages/result";
        }
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <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>/</url-pattern>
    </servlet-mapping>

    <!--过滤器编码-->
    <filter>
        <filter-name>encoding</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录</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="/day0831/result.do"  commandName="student" modelAttribute="student">
    <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="password">密码:</form:label></td>
        <td><form:input path="password" /></td>
        <td><form:errors path="password" cssClass="error" /></td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" value="提交" /></td>
      </tr>
    </table>
  </form:form>
  </body>
</html>

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h4>学生信息如下:</h4>
姓名:${student.getName()}<br>
密码:${student.getPassword()}
</body>
</html>

Student.java

package my.model;
import java.io.Serializable;
public class Student implements Serializable {
    private String name;
    private String password;
	//此处省略构造方法和setter()、getter()方法、toString()方法,自行补全...
}
运行

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

分析:

1、StudentContorller控制器中需要绑定校验器:

	@InitBinder
    public void InitBinder(DataBinder binder){
        // 设置校验器类为StudentValidator
        binder.setValidator(studentValidator);
    }

2、然后上面的校验器需要获得一个实例指明:studentValidator校验器

	@Autowired
    @Qualifier("studentValidator")
    private StudentValidator studentValidator;

3、有了校验器,我们还需要一个模型保存表单的数据

	@RequestMapping(value="/index.do",method=RequestMethod.GET)
    public String index(Model model){
        model.addAttribute("student",student);
        return "index";
    }

4、然后需要对保存的数据经过校验器判断是否有错误,将保存在Errors对象中错误的错误进行判断是否存在错误,决定页面的跳转去向…

	@RequestMapping(value="/result.do",method=RequestMethod.POST)
    public String register(@Validated Student student, Errors errors){
        if (errors.hasFieldErrors()){
            return "index";
        }else{
            return "pages/result";
        }
    }

5、未完待续…

发布了49 篇原创文章 · 获赞 38 · 访问量 8314

猜你喜欢

转载自blog.csdn.net/Mr_C_python/article/details/100096532