Spring MVC异常处理实例
以下内容引用自http://wiki.jikexueyuan.com/project/spring/mvc-framework/spring-exception-handling-example.html:
例子:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jsoft.testspring</groupId>
<artifactId>testexception</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>testexception Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Servlet Library -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency> <!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Web -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Web MVC -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> </dependencies>
<build>
<finalName>testexception</finalName>
<plugins>
<!-- Config: Maven Tomcat Plugin -->
<!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin -->
<!-- http://tomcat.apache.org/maven-plugin-2.0/tomcat7-maven-plugin/plugin-info.html -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<!-- Config: contextPath and Port (Default:8080) -->
<!--
<configuration>
<path>/</path>
<port>8899</port>
</configuration>
-->
</plugin>
<!-- Config: Maven Jetty Plugin -->
<!-- http://mvnrepository.com/artifact/org.mortbay.jetty/jetty-maven-plugin -->
<!-- http://www.eclipse.org/jetty/documentation/current/jetty-maven-plugin.html -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.3.v20170317</version>
<!-- Config: contextPath and Port (Default:8080) -->
<!--
<configuration>
<httpConnector>
<port>8899</port>
</httpConnector>
<webAppConfig>
<contextPath>/</contextPath>
</webAppConfig>
</configuration>
-->
</plugin>
</plugins>
</build>
</project>
web.xml:
<web-app id="WebApp_ID" version="3.0"
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_3_0.xsd"> <display-name>Spring MVC Application</display-name> <servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 默认:[servlet-name]-servlet.xml -->
<!-- 通过初始化参数,指定xml文件的位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>
springmvc-context.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.jsoft.testspring"/> <context:annotation-config/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.jsoft.testspring.testexception.SpringException">
ExceptionPage
</prop>
</props>
</property>
<property name="defaultErrorView" value="error" />
</bean>
</beans>
说明:指定ExceptionPage作为一个异常视图,当SpringException发生时触发,另外,如果有任何其他类型的异常发生,通用的视图error就会触发。
Student.java:
package com.jsoft.testspring.testexception; 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;
}
}
SpringException.java:
package com.jsoft.testspring.testexception; public class SpringException extends RuntimeException {
private String exceptionMsg; public SpringException(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
} public String getExceptionMsg() {
return this.exceptionMsg;
} public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
StudentController.java:
package com.jsoft.testspring.testexception; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; @Controller
public class StudentController { @RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
} @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
@ExceptionHandler({ SpringException.class })
public String addStudent(Student student, ModelMap model) {
if (student.getName().length() < 5) {
throw new SpringException("Given name is too short");
} else {
model.addAttribute("name", student.getName());
}
if (student.getAge() < 10) {
throw new SpringException("Given age is too low");
} else {
model.addAttribute("age", student.getAge());
}
model.addAttribute("id", student.getId());
return "result";
}
}
student.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body> <h2>Student Information</h2>
<form:form method="POST" action="addStudent">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body> <h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
ExceptionPage.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body> <h2>Spring MVC Exception Handling</h2> <h3>${exception.exceptionMsg}</h3> </body>
</html>
error.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring Error Page</title>
</head>
<body> <p>An error occured, please contact webmaster.</p> </body>
</html>
测试工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test19/testexception
Spring MVC异常处理实例的更多相关文章
- Spring MVC异常处理代码完整实例
Spring MVC异常处理流程: 提供构造方法传值: 配置异常处理器的bean
- Spring MVC异常处理SimpleMappingExceptionResolver
Spring MVC异常处理SimpleMappingExceptionResolver[转] (2012-12-07 13:45:33) 转载▼ 标签: 杂谈 分类: 技术分享 Spring3.0中 ...
- Spring MVC框架实例
Spring MVC 背景介绍 Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块.使用 Spring 可插入的 MVC 架构,能够选择是使用内置的 Spring Web 框架还是 ...
- Spring系列(七) Spring MVC 异常处理
Servlet传统异常处理 Servlet规范规定了当web应用发生异常时必须能够指明, 并确定了该如何处理, 规定了错误信息应该包含的内容和展示页面的方式.(详细可以参考servlet规范文档) 处 ...
- Spring MVC异常处理详解
Spring MVC中异常处理的类体系结构 下图中,我画出了Spring MVC中,跟异常处理相关的主要类和接口. 在Spring MVC中,所有用于处理在请求映射和请求处理过程中抛出的异常的类,都要 ...
- Spring MVC Framework 实例
一 SpringMVC基础入门,创建一个HelloWorld程序 1 首先,导入SpringMVC需要的jar包. commons-logging-<version>.jar spring ...
- Spring MVC异常处理
Spring Mvc 中异常处理,一般有两种解决办法: 一.利用org.springframework.web.servlet.handler.SimpleMappingExceptionResolv ...
- Spring MVC异常处理详解(转)
下图中,我画出了Spring MVC中,跟异常处理相关的主要类和接口. 在Spring MVC中,所有用于处理在请求映射和请求处理过程中抛出的异常的类,都要实现HandlerExceptionReso ...
- Spring MVC异常处理详解 ExceptionHandler good
@ControllerAdvice(basePackageClasses = AcmeController.class) public class AcmeControllerAdvice exten ...
随机推荐
- SEO 第二章
SEO第二章 1. 掌握搜索引擎工作原理(重点) 2. 了解百度算法 3. 关键词的分类 一.什么是搜索引擎? 搜索引擎是用来实现搜索服务的,说白了搜索引擎也属于一种网站. 浏览器是用来加载网站 ...
- DROP SCHEMA - 删除一个模式
SYNOPSIS DROP SCHEMA name [, ...] [ CASCADE | RESTRICT ] DESCRIPTION 描述 DROP SCHEMA 从数据库中删除模式. 模式只能被 ...
- mysql利用binlog恢复数据
需求:需要给开发提供一个2018年9月30号的数据,按照我们公司正常备份策略来说,直接找到对应时间的备份数据,解压导入即可,恰好这个时间节点的数据没有,只备份到2018年9月25号的,糟糕了吧 咋办呢 ...
- Crashlytics Android 异常报告统计管理
http://www.infoq.com/cn/articles/crashlytics-crash-statistics-tools 简介 Crashlytic 成立于2011年,是专门为移动应用开 ...
- 字符串 || CodeForces 591B Rebranding
给一字符串,每次操作把字符串中的两种字母交换,问最后交换完的字符串是多少 arr数组记录每个字母最后被替换成了哪个字母 读入字符前面加一空格 scanf(" %c %c", &am ...
- CSS中列表项list样式
CSS列表属性 属性 描述 list-style-属性 用于把所有用于列表的属性设置于一个声明中. list-style-image 将图象设置为列表项标志. list-style-position ...
- [JOYOI] 1415 西瓜种植
题目描述 笨笨种了一块西瓜地,但这块西瓜地的种植范围是一条直线的-- 笨笨在一番研究过后,得出了m个结论,这m个结论可以使他收获的西瓜最多. 笨笨的结论是这样的: 从西瓜地B处到E处至少要种植T个西瓜 ...
- 条款4:确定对象被使用前已被初始化(Make sure that objects are initialized before they're used)
其实 无论学何种语言 ,还是觉得要养成先声明后使用,先初始化再使用. 1.永远在使用对象之前先将其初始化. 内置类型: 必须手工完成. 内置类型以外的:使用构造函数完成.确保每一个构造函数都将对象的一 ...
- vue 页面过渡效果
App.vue 模板 <template> <div id="app"> <transition :name="transition&quo ...
- Activiti数据表
--1:资源库流程规则表SELECT * FROM JEESITE.act_re_deployment --部署信息表SELECT * FROM JEESITE.act_re_model --流程设计 ...