SpringMVC的异常处理

来源:互联网 发布:ubuntu 分区命令 编辑:程序博客网 时间:2024/05/20 17:40

数据异常处理


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



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. */@Controllerpublic 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. */@Controllerpublic 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. */@Controllerpublic 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>

并且如果我们在日期哪里输入的是错误信息(汉字)的我们会跳转回当前页面 ,并且保留数据,我们已经把数据存了起来。

原创粉丝点击