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";
}
啦啦啦
SpringMVC -- 梗概--源码--贰--异常管理的更多相关文章
- SpringMVC -- 梗概--源码--贰--下载
1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...
- SpringMVC -- 梗概--源码--贰--上传
1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...
- SpringMVC -- 梗概--源码--贰--拦截器:Interceptor
附:实体类 1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app versi ...
- SpringMVC -- 梗概--源码--贰--RestFul收参(了解) @PathVariable
1>定制方式: //如下两个路径都可以访问到如下方法,请求路径不同,则name61和pwd61匹配到的值不同 //http://localhost:8989/appname/ful/lime/1 ...
- SpringMVC -- 梗概--源码--贰--mvc:annotation-driven
1>在springMVC的处理流程中,有两个重要组件:HandlerMapping和HandlerAdapter 分别负责解析Handler和执行Handler 2>如果配置了<mv ...
- SpringMVC -- 梗概--源码--贰--静态资源的访问问题
配置:<mvc:default-servlet-handler/> 1>静态资源:除了Servlet.Controller之外的资源,如:js,css,png,html等 2> ...
- SpringMVC -- 梗概--源码--壹--springMVC json处理
附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...
- SpringMVC -- 梗概--源码--壹--数据传递
附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...
- SpringMVC -- 梗概--源码--壹--跳转
1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...
随机推荐
- 百度地图Api进阶教程-创建标注和自定义标注3.html
<!DOCTYPE html> <html> <head> <meta name="viewport" content="ini ...
- EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.
启动两个client,过了一会,停了其中一个,访问注册中心时,界面上显示了红色粗体警告信息: 查阅了很多资料,终于了解了中间的问题.现将理解整理如下: Eureka server和client之间每隔 ...
- iOS 实时音频采集与播放Audio Unit使用
前言 在iOS中有很多方法可以进行音视频采集.如 AVCaptureDevice, AudioQueue以及Audio Unit.其中 Audio Unit是最底层的接口,它的优点是功能强大,延迟低; ...
- PHP 日期 加减 月数,天数,周数,小时,分,秒等等
实就是strtotime 这个内置函数 //PHP 日期 加减 周 date("Y-m-d",strtotime("2013-11-12 +1 week")) ...
- SparkR(R on Spark)编程指南 含 dataframe操作
SparkR(R on Spark)编程指南 Spark 2015-06-09 28155 1评论 下载为PDF 为什么不允许复制 关注iteblog_hadoop公众号,并在这里评论区留言 ...
- ASP.NET中使用jQuery插件实现图片幻灯效果
参照网上的资料及提供的jQuery插件实现图片幻灯效果. 1.页面前台代码: //头部引用 <head runat="server"><title>< ...
- 【Qt开发】QThread 实用技巧、误区----但文档中没有提到
本文主要内容: 在任务一中,用 四 种方式实现:点击界面按钮,开线程运行一段程序,结果显示在一个Label上.1. 用不正确的方式得到看似正确的结果2. 用Qt Manual 和 例子中使用的方法3. ...
- 总结这两天连续干掉的bug In 创新实训 智能自然语言交流系
临近项目合并,在pre合并中出现相当多的hug,遂记之 ps:这只是总结一下提纲,具体的方法在前文的博文中都详细记录.总结了. 平台的移植兼容性,虽然是跨平台的java,但是依旧有很多的意外: 1.从 ...
- JDBC排序数据实例
在本教程将演示如何在JDBC应用程序中,从数据库表中查询数据记录,在查询语句中将使用asc和desc关键字按升序或降序对记录进行排序.在执行以下示例之前,请确保您已经准备好以下操作: 具有数据库管理员 ...
- JUnit断言
在本节中,我们将介绍一些断言方法.所有这些方法都受到 Assert 类扩展了java.lang.Object类并为它们提供编写测试,以便检测故障.下表中有一种最常用的断言方法的更详细的解释. 断言 描 ...