附:实体类

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 -- 梗概--源码--贰--异常管理的更多相关文章

  1. SpringMVC -- 梗概--源码--贰--下载

    1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...

  2. SpringMVC -- 梗概--源码--贰--上传

    1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...

  3. SpringMVC -- 梗概--源码--贰--拦截器:Interceptor

    附:实体类 1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app versi ...

  4. SpringMVC -- 梗概--源码--贰--RestFul收参(了解) @PathVariable

    1>定制方式: //如下两个路径都可以访问到如下方法,请求路径不同,则name61和pwd61匹配到的值不同 //http://localhost:8989/appname/ful/lime/1 ...

  5. SpringMVC -- 梗概--源码--贰--mvc:annotation-driven

    1>在springMVC的处理流程中,有两个重要组件:HandlerMapping和HandlerAdapter 分别负责解析Handler和执行Handler 2>如果配置了<mv ...

  6. SpringMVC -- 梗概--源码--贰--静态资源的访问问题

    配置:<mvc:default-servlet-handler/> 1>静态资源:除了Servlet.Controller之外的资源,如:js,css,png,html等 2> ...

  7. SpringMVC -- 梗概--源码--壹--springMVC json处理

    附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...

  8. SpringMVC -- 梗概--源码--壹--数据传递

    附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...

  9. SpringMVC -- 梗概--源码--壹--跳转

    1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...

随机推荐

  1. jQuery(五):文本操作

    text()可以获取或设置元素的文本内容.例如: 示例: <!DOCTYPE html> <html lang="en"> <head> < ...

  2. Spring Cloud Config 配置刷新

    客户端进行刷新操作. 1.添加 actuator包,这样 /refresh url才处于可用状态. <dependency> <groupId>org.springframew ...

  3. eclipse format xml

    eclipse版本信息:Version: Luna Release (4.4.0) eclipse默认使用Tab缩进,显得不是那么专业. 因为不同的系统对Tab的支持是不一样的,所以在不同的系统或者编 ...

  4. 25个顶级的jQuery表格插件

    jQuery 表格插件可以让你创建各种各样的表格布局,表格布局是报纸和杂志中最常见的布局,现在的网站中也很常见,在这篇文章中,我向大家推荐25个jQuery 的表格插件,你可以任意控制表格的行和列,用 ...

  5. why "Everything" is so fast?

    Everything并不扫描整个磁盘,只是读取磁盘上的USN日志,所以速度飞快.但因此缺点也明显:1.只支持NTFS格式的分区,因为USN日志是NTFS专有的.在FAT.FAT32格式分区上无法使用E ...

  6. Servlet输出PDF文档方法

    概述 Java Servlet 编程可以很方便地将 HTML 文件发送到客户端的 Web 浏览器.然而许多站点还允许访问非 HTML 格式的文档,包括 Adobe PDF.Microsoft Word ...

  7. Maven自动化部署

    在项目开发中,通常是部署过程包含以下步骤 检入代码在建项目全部进入SVN或源代码库中,并标记它. 从SVN下载完整的源代码. 构建应用程序. 生成输出要么WAR或EAR文件存储到一个共同的网络位置. ...

  8. TPshop标签

    很多cms 中有很多 标签, 商品标签 文章标签  列表标签  几十个标签, 让开发者头疼, 难记,  TPshop开发者考虑到这点, 用了一个万能标签, 开发者非常方便实用 TPshop万能标签只要 ...

  9. 初识ZooKeeper与集群搭建实例

    原文链接:http://www.linuxidc.com/Linux/2015-02/114230.htm zookeeper是什么 Zookeeper,一种分布式应用的协作服务,是Google的Ch ...

  10. LVS 实现负载均衡原理及安装配置详解

    负载均衡集群是 load balance 集群的简写,翻译成中文就是负载均衡集群.常用的负载均衡开源软件有nginx.lvs.haproxy,商业的硬件负载均衡设备F5.Netscale.这里主要是学 ...