SpringMVC -- 梗概--源码--贰--异常管理

附:实体类

Class : User

package com.c61.entity;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import com.alibaba.fastjson.annotation.JSONField;

public class User {
    private Integer id;
    private String name;
    //@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd")//定制在接收请求参数时的日期格式
    @JSONField(format="yyyy-MM-dd")//作用在java序列化成json时
    private Date birth;
    private String dateStr;
    
    public String getDateStr() {
        return dateStr;
    }
    public void setDateStr(String dateStr) {
        this.dateStr = dateStr;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        this.dateStr=format.format(birth);
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
    }
    public User(){}
    public User(Integer id, String name, Date birth) {
        super();
        this.id = id;
        this.name = name;
        this.birth = birth;
    }
    
}

Class : LoginErrorException

package com.c61.exception;

public class LoginErrorException extends RuntimeException{
    
    public LoginErrorException(){}
    public LoginErrorException(String msg){
        super(msg);
    }
}

Class : AException

package com.c61.exception;

public class AException extends RuntimeException{
    
    public AException(){}
    public AException(String msg){
        super(msg);
    }
}

Class : UserServiceImpl

package com.c61.service;

import com.c61.exception.AException;
import com.c61.exception.LoginErrorException;

public class UserServiceImpl implements UserService{

    public void login(String username, String password) {
        //登录业务
        if(!"c61".equals(username)){
            //日志
            throw new LoginErrorException("用户名无效");
        }else if(!"123".equals(password)){
            //日志
            throw new LoginErrorException("密码无效");
        }else if(username.length()<10){
            throw new AException("test");
        }
        //正常的登录逻辑控制
        //......
    }
}

1.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 前端控制器 
         /=默认的url-pattern
         /a/b/c  /a
         
         /a/d/c
         /a/d
         /a
         /
         *注意:此控制器默认加载/WEB-INF下的xxx-servlet.xml文件
                        :其中xxx等于【DispatcherServlet的配置名】
  -->
  <servlet>
      <servlet-name>mvc61</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:mvc62.xml</param-value>
      </init-param>
      <!-- 随项目启动而启动 -->
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>mvc61</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 专治Post请求参数乱码 -->
  <filter>
      <filter-name>encoding61</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <!-- 将请求的编码方式设置为utf-8 -->
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>encoding61</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

2.配置SpringMVC.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- xmlns:xml name space 是每一个schema唯一标识 -->
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 
       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-3.2.xsd
                              http://www.springframework.org/schema/context
                              http://www.springframework.org/schema/context/spring-context-3.2.xsd
                              http://www.springframework.org/schema/mvc
                              http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 扫描所有控制器中的注解 -->
    <context:component-scan base-package="com.c61.controller"></context:component-scan>
    <!-- 
        MVC中基于注解开发,导入注解驱动
        <mvc:annotation-driven/>
     -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 支持的格式:application/json -->
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!-- 视图解析器:解析视图
         控制器方法的返回值,会被视图解析器捕获。"abc"
         根据捕获的内容,解析出一个视图地址:/abc.jsp
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 
        静态资源:html,js,css,jpg
        访问404 解决
     -->
     <mvc:default-servlet-handler/>
     
     <!-- 声明异常处理器 -->
     <bean class="com.c61.ex.resolver.MyExceptionResolver"></bean>
     
     <!-- 拦截器配置 -->
     <!-- 
         /a/b
         inter1
         inter2
         拦截顺序:先配置先拦截
         具体顺序:pre1==pre2==contorller==post2==post1==after2==after1
      -->
     <mvc:interceptors>
         <mvc:interceptor>
             <!-- 定义要拦截的路径 
                  /inter/*  匹配   /inter/a   /inter/b    inter/cssdafasfsafs
                                                  不能匹配/inter/a/b
                 /inter/** 匹配 /inter/a  /inter/xxsjaflsajf   /inter/a/b/c/e/d/xxxcvx
                 *注意:exclude-mapping不能单独使用。要配合mapping使用
                             :在mapping匹配的范围中排除一些个。
             -->
             <mvc:mapping path="/inter/**"/>
             <mvc:mapping path="/a/b"/>
             <mvc:mapping path="/c/**"/>
             <mvc:exclude-mapping path="/inter/test/*"/>
             <mvc:exclude-mapping path="/c/b/**"/>
             <!-- 声明拦截器 -->
             <bean class="com.c61.interceptor.MyInterceptor"/>
         </mvc:interceptor>
         <mvc:interceptor>
             <!-- 定义要拦截的路径 -->
             <mvc:mapping path="/inter/test"/>
             <!-- 声明拦截器 -->
             <bean class="com.c61.interceptor.MyInterceptor2"/>
         </mvc:interceptor>
     </mvc:interceptors>
     <!-- 声明文件上传解析器 
           注意:此解析器,id必须为:multipartResolver
     -->
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- 最大允许的上传大小    byte -->
         <property name="MaxUploadSize" value="2097152"></property>
     </bean>
     <!-- 
         注册,验证码生成器
      -->
      <bean id="captcha" class="com.google.code.kaptcha.servlet.KaptchaExtend">
        <constructor-arg>
            <props>  
                <!-- 是否有边框 边框颜色 边框粗细 -->
                <prop key="kaptcha.border">no</prop>  
                <prop key="kaptcha.border.color">105,179,90</prop>  
                <prop key="kaptcha.border.thickness">20</prop>
                <prop key="kaptcha.textproducer.font.color">black</prop>  
                <prop key="kaptcha.image.width">200</prop>  
                <prop key="kaptcha.image.height">50</prop>  
                <prop key="kaptcha.textproducer.font.size">40</prop>  
                <prop key="kaptcha.session.key">code61</prop>  
                <prop key="kaptcha.textproducer.char.length">4</prop>  
                <prop key="kaptcha.textproducer.font.names">Arial,Courier</prop> 
              <!--   <prop key="kaptcha.background.clear.from">black</prop> 
                <prop key="kaptcha.background.clear.to">255,0,0</prop>  -->
            </props>  
        </constructor-arg>
    </bean>
</beans>

3.配置控制器

Class : ExceptionController

package com.c61.controller;

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

import com.c61.service.UserService;
import com.c61.service.UserServiceImpl;


@Controller
@RequestMapping("/ex")
public class ExceptionController {
    
    /*private UserService us=new UserServiceImpl();
    public String login(String username,String password){
        try{
            us.login(username, password);
        }catch(LoginErrorException e){
            return "redirect:/login.jsp";
        }catch(AException e){
            return "redirect:/xxx.jsp";
        }catch(Exception e){
            
        }
        return "forward:/index.jsp";
    }*/
    private UserService us=new UserServiceImpl();
    @RequestMapping("/login")
    public String login(String username,String password){
        us.login(username,password);
        return "forward:/index.jsp";
    }
}

4.定制异常管理器

Class : MyExceptionResolver

package com.c61.ex.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.c61.exception.AException;
import com.c61.exception.LoginErrorException;

/*
 * 异常处理器:所有Controller中抛出的所有异常,都由此处理器接收并处理。
 */
public class MyExceptionResolver implements HandlerExceptionResolver{
    
    /**
     * 主体逻辑:自动捕获Controller中的异常,每当Controller中抛出异常时,就会执行。
     * param:ex=当前抛出的异常
     *       req=请求对象
     *       res=响应对象
     *       handler=抛出异常的控制器方法
     */
    public ModelAndView resolveException(HttpServletRequest req,
            HttpServletResponse res, Object handler, Exception ex) {
        System.out.println(ex.getClass());
        //System.out.println(req.getClass()+" "+res.getClass()+" "+handler.getClass());
        System.out.println("异常处理~~~~"+ex.getMessage());
        ModelAndView mav=new ModelAndView();
        //识别异常
        if(ex instanceof LoginErrorException){
            mav.setViewName("redirect:/error1.jsp");
        }else if(ex instanceof AException){
            mav.setViewName("redirect:/error2.jsp");
        }else if(ex instanceof MaxUploadSizeExceededException){
            mav.setViewName("redirect:/error4.jsp");
        }else{
            mav.setViewName("redirect:/error3.jsp");
        }
        return mav;
    }

}

5.声明异常管理器

XML : SpringMVC.xml

     <!-- 声明异常处理器 -->
     <bean class="com.c61.ex.resolver.MyExceptionResolver"></bean>

6.配置视图

View : errer1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    This is my error1 JSP page. <br>
  </body>
</html>

View : errer2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    This is my error2 JSP page. <br>
  </body>
</html>

View : errer3.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    This is my error3 JSP page. <br>
  </body>
</html>

View : errer4.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    请上传小于2M的文件
  </body>
</html>

异常管理

定制异常管理器

public class MyExceptionResolver implements HandlerExceptionResolver{
    /**
     * 主体逻辑:自动捕获Controller中的异常,每当Controller中抛出异常时,就会执行。
     * param:ex=当前抛出的异常
     *       req=请求对象
     *       res=响应对象
     *       handler=抛出异常的控制器方法
     * 返回值:ModelAndView=用来返回错误页面
     */
    public ModelAndView resolveException(HttpServletRequest req,
            HttpServletResponse res, Object handler, Exception ex) {
        ModelAndView mav=new ModelAndView();
        //识别异常
        if(ex instanceof LoginErrorException){
            mav.setViewName("redirect:/error1.jsp");
        }else if(...){}
        ...
        return mav;
    }
}

声明

<bean class="com.c61.ex.resolver.MyExceptionResolver"></bean>

异常管理器作用

作用:统一抽取了所有控制器中的异常处理逻辑
抽取前:
    public String login(String username,String password){
        try{
            us.login(username, password);
        }catch(LoginErrorException e){
            return "redirect:/login.jsp";
        }catch(AException e){
            return "redirect:/xxx.jsp";
        }catch(Exception e){

        }
        return "forward:/index.jsp";
    }
抽取后:
    public String login(String username,String password){
        us.login(username,password);
        return "forward:/index.jsp";
    }

啦啦啦

原文地址:https://www.cnblogs.com/ClassNotFoundException/p/6714736.html