SpringMVC的异常处理

本文介绍Spring MVC框架中的异常处理机制及数据校验方法,包括自定义异常类、异常控制器、日期格式转换等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据异常处理


首先这个小示例,是我们在代码中什么一个错然后让他遇到错跳转页面:



1.我们执行的时候在地址栏输入我们对应的@RequestMapping的值然后,  对应走页面,

package cn.happy.springmvc07exection;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by linlin on 2017/8/28.
 */
@Controller
public class FirstController {
    @RequestMapping("/first")
    public String list(){
        //构造异常
        int result=5/0;
        return "/WEB-INF/first.jsp";
    }


}


<context:component-scan base-package="cn.happy.springmvc07exection"></context:component-scan>
  <!--异常处理器-->
 <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="defaultErrorView" value="/error.jsp"></property>
    <property name="exceptionAttribute" value="ex"></property>

我们对应就会走error页面。


==================================================================

第二个 根据年龄和 name名字判断。

效果:



首先我们建一个实体类:

package cn.happy.springmvc07exection.exceptions;

/**
 * Created by Happy on 2017-08-20.
 */
public class UserInfo {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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


自己定义一个异常:

package cn.happy.springmvc07exection.exceptions;

/**
 * Created by linlin on 2017/8/28.
 */
public class UserException  extends Exception {
    public UserException() {
    }

    public UserException(String message) {
        super(message);
    }
}


在定义2个异常类:

package cn.happy.springmvc07exection.exceptions;

/**
 * Created by linlin on 2017/8/28.
 */
public class NameException extends UserException {
    public NameException() {
    }

    public NameException(String message) {
        super(message);
    }
}

package cn.happy.springmvc07exection.exceptions;

/**
 * Created by linlin on 2017/8/28.
 */
public class AgeException extends  UserException {
    public AgeException() {
    }

    public AgeException(String message) {
        super(message);
    }
}

这个Controller  就是判断用的,我们在页面输入值 ,如果年龄大于80或者name不等于admin我们就走异常。


package cn.happy.springmvc07exection;

import cn.happy.springmvc07exection.exceptions.AgeException;
import cn.happy.springmvc07exection.exceptions.NameException;
import cn.happy.springmvc07exection.exceptions.UserException;
import cn.happy.springmvc07exection.exceptions.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by linlin on 2017/8/28.
 */
@Controller
public class SecondController {
        @RequestMapping("/firstExcetpion")
        public String doFirst(UserInfo info) throws UserException {
            if (!info.getName().equals("admin")) {
                //不是admin,抛出一个Name出错异常
                throw new NameException("用户名异常");
            }
            if (info.getAge()>60) {
                throw new AgeException("年龄异常");
            }
            return "/index.jsp";
        }
    }



页面:

<%--
  Created by IntelliJ IDEA.
  User: linlin
  Date: 2017/8/28
  Time: 10:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page isELIgnored="false" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>异常提升</h1>
<form action="${pageContext.request.contextPath }/firstExcetpion" method="post">
    姓名:<input name="name"/><br/><br/>
    年龄:<input name="age"/><br/><br/>
    <input type="submit" value="注册"/>
</form>

</body>
</html>

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">

<context:component-scan base-package="cn.happy.springmvc07exection"></context:component-scan>
  <!--异常处理器-->
 <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="defaultErrorView" value="/error.jsp"></property>
    <property name="exceptionAttribute" value="ex"></property>

   <property name="exceptionMappings">
      <props>
        <prop key="cn.happy.springmvc07exection.exceptions.AgeException">Age.jsp</prop>
        <prop key="cn.happy.springmvc07exection.exceptions.NameException">Name.jsp</prop>
      </props>
    </property>
  </bean>
<!--<bean class="cn.happy.springmvc08selfexception.exceptionhandler.MyHanlderExceptionResolver"></bean>-->
</beans>

数据校验(日期):、




package cn.happy.springmvc10;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * Created by linlin on 2017/8/28.
 */
public class MyConverter implements Converter<String,Date> {
    public Date convert(String source) {
        SimpleDateFormat sdf=getDateFormat(source);
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SimpleDateFormat getDateFormat(String source) {
        SimpleDateFormat sdf=null;
        if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}",source)){
            sdf=new SimpleDateFormat("yyyy-MM-dd");
        }else if (Pattern.matches("\\d{4}/\\d{2}/\\d{2}",source)){
            sdf=new SimpleDateFormat("yyyy/MM/dd");
        }else if (Pattern.matches("\\d{4}\\d{2}\\d{2}",source)){
            sdf=new SimpleDateFormat("yyyyMMdd");
        }
        return sdf;
    }
}

package cn.happy.springmvc10;

import org.springframework.beans.TypeMismatchException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by linlin on 2017/8/28.
 */
@Controller
public class FirstController {

    @ExceptionHandler(TypeMismatchException.class)
    public ModelAndView exceptionHandler(HttpServletRequest request){
        ModelAndView mv=new ModelAndView();
        //放入request作用域中
        mv.addObject("date",request.getParameter("birthday"));
        mv.setViewName("MyConverter.jsp");
        return mv;
    }
    @RequestMapping("/first")
    public String doFirst(Date birthday, int age){
        return "index.jsp";
    }
}



页面传值在Controller进行校验:

<%--
  Created by IntelliJ IDEA.
  User: linlin
  Date: 2017/8/28
  Time: 12:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page isELIgnored="false" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>类型转换</h1>
<form action="${pageContext.request.contextPath }/first" method="post">
    出生日期:<input name="birthday" value="${date}"/><br/><br/>
    年龄:<input name="age" value="${age}"/><br/><br/>
    <input type="submit" value="注册"/>
</form>
</body>
</html>

并且如果我们在日期哪里输入的是错误信息(汉字)的我们会跳转回当前页面 ,并且保留数据,我们已经把数据存了起来。
基于开源大模型的教学实训智能体软件,帮助教师生成课前备课设计、课后检测问答,提升效率与效果,提供学生全时在线练习与指导,实现教学相长。 智能教学辅助系统 这是一个智能教学辅助系统的前端项目,基于 Vue3+TypeScript 开发,使用 Ant Design Vue 作为 UI 组件库。 功能模块 用户模块 登录/注册功能,支持学生和教师角色 毛玻璃效果的登录界面 教师模块 备课与设计:根据课程大纲自动设计教学内容 考核内容生成:自动生成多样化考核题目及参考答案 学情数据分析:自动化检测学生答案,提供数据分析 学生模块 在线学习助手:结合教学内容解答问题 实时练习评测助手:生成随练题目并纠错 管理模块 用户管理:管理员/教师/学生等用户基本管理 课件资源管理:按学科列表管理教师备课资源 大屏概览:使用统计、效率指数、学习效果等 技术栈 Vue3 TypeScript Pinia 状态管理 Ant Design Vue 组件库 Axios 请求库 ByteMD 编辑器 ECharts 图表库 Monaco 编辑器 双主题支持(专业科技风/暗黑风) 开发指南 # 安装依赖 npm install # 启动开发服务器 npm run dev # 构建生产版本 npm run build 简介 本项目旨在开发一个基于开源大模型的教学实训智能体软件,帮助教师生成课前备课设计、课后检测问答,提升效率与效果,提供学生全时在线练习与指导,实现教学相长。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值