今日知识

1. SpringMVC自定义异常处理
2. SpringMVC的interceptor(过滤器)

SpringMVC自定义异常处理

1.web.xml正常写

<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--<load-on-startup>1</load-on-startup>-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

2. application.xml写法

<context:component-scan base-package="com.rqy"/>
<mvc:annotation-driven/>
<!--配置springmvc视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>

3. Controller处理层

@Controller
public class HelloController {
@RequestMapping("hello")
public String hello(int type) throws Exception {
if (type==1){
throw new MyException("你的用户名过长");//自定义异常
}else if (type==2){
throw new FileSizeException();
}else if (type>2){
throw new UnknownParamException();
}
return "hello" ;
}
}

4. 自定义异常MyException-->其他异常也类似

public class MyException extends Exception {
public MyException(String message){
super(message);
}
}

5. 注册自定义异常处理器(会自动拦截异常)

* 避免直接在页面显示异常信息,我们自定义异常处理器,抛出对应的异常时将转发到不同的页面上。
* 案例:
* @Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
System.out.println(o);
if (e instanceof MyException) {
MyException myException = (MyException) e;
modelAndView.addObject("content", myException.getMessage());
modelAndView.setViewName("customException");
} else if (e instanceof FileSizeException) { modelAndView.setViewName("fileException");
} else if (e instanceof UnknownParamException) {
modelAndView.setViewName("paramException"); }
return modelAndView;
}
}
* 其中customException,fileException,paramException对应的jsp页面
* 例如:页面打印出: 自定义的异常 ${content},即可。

SpringMVC的interceptor(过滤器)

1. 原理:就是过滤器

2. ctrl+o:直接可以调出实现接口的方法

3. implements HandlerInterceptor

* public class MySecondInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle2");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle2");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion2");
}
}

4. 如果一个为false的话,下面的全部流程都不进行

5. xml配置

*     <mvc:interceptors>
<!--全部请求都通过interceptor-->
<!--/**-->
<bean class="com.rqy.interceptor.MyFirstInterceptor"/>
<bean class="com.rqy.interceptor.MySecondInterceptor"/>
<!--<ref bean="interceptor3"/>-->
<!--interc拦截部分请求-->
<!--user/query
user/add
user/register-->
<mvc:interceptor>
<!--localhost/user/a yes-->
<mvc:mapping path="/user/**"/>
<bean class="com.rqy.interceptor.MyThirdInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>

6. 结论:preHandle全为true才会执行到requestMapping和postHandle

7. 案例(用户未登录拦截到login.jsp)

* public class MyFirstInterceptor implements HandlerInterceptor {
//当返回值为false时不能够进入RequestMapping对应的方法
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle1");
String username = request.getParameter("username");
if (username==null|| "".equals(username)){
return true;//如果没有参数提交,继续验证下面方法postHandle,看看用户是否登录了
}else {
request.getSession().setAttribute("username",username);
return true; //username不为空,意味用户登录操作,不进行拦截
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
String username = (String) request.getSession().getAttribute("username");
if (username==null|| "".equals(username)){
modelAndView.setViewName("login");//用户未登录返回login界面
}else {
modelAndView.addObject("username",username);
modelAndView.setViewName("hello");
}
System.out.println("postHandle1");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion1");
}
}

09-SpringMVC03的更多相关文章

  1. Windows7WithSP1/TeamFoundationServer2012update4/SQLServer2012

    [Info   @09:03:33.737] ====================================================================[Info   @ ...

  2. 《HelloGitHub月刊》第09期

    <HelloGitHub>第09期 兴趣是最好的老师,<HelloGitHub>就是帮你找到兴趣! 前言 转眼就到年底了,月刊做到了第09期,感谢大家一路的支持和帮助

  3. js正则表达式校验非零的正整数:^[1-9]\d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^\+?[1-9][0-9]*$

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. iOS系列 基础篇 09 开关、滑块和分段控件

    iOS系列 基础篇 09 开关.滑块和分段控件 目录: 案例说明 开关控件Switch 滑块控件Slider 分段控件Segmented Control 1. 案例说明 开关控件(Switch).滑块 ...

  5. http://www.cnblogs.com/Lawson/archive/2012/09/03/2669122.html

    http://www.cnblogs.com/Lawson/archive/2012/09/03/2669122.html

  6. u-boot-2010.09移植(A)

    第一阶段 1.开发环境 系统:centOS6.5           linux版本:2.6.32         交叉编译器:buildroot-2012.08 以上工具已经准备好,具体安装步骤不再 ...

  7. u-boot-2010.09移植(B)

    前面我们的u-boot只是在内存中运行,要想在nandflash中运行,以达到开机自启的目的,还需作如下修改 一.添加DM9000网卡支持 1.修改board/fl2440/fl2440.c中的boa ...

  8. Linux JDK 安装及卸载 http://www.cnblogs.com/benio/archive/2010/09/14/1825909.html

    参考:http://www.cnblogs.com/benio/archive/2010/09/14/1825909.html

  9. c#用正则表达式判断字符串是否全是数字、小数点、正负号组成 Regex reg = new Regex(@"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$");

    Regex reg = new Regex(@"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][ ...

  10. JavaScript学习09 函数本质及Function对象深入探索

    JavaScript学习09 函数本质及Function对象深入探索 在JavaScript中,函数function就是对象. JS中没有方法重载 在JavaScript中,没有方法(函数)重载的概念 ...

随机推荐

  1. await Task.Yield()和await Task.CompletedTask有什么不同

    有时候我们在代码中要执行一些非常耗时的操作,我们不希望这些操作阻塞调用线程(主线程)的执行,因为调用线程(主线程)可能还有更重要的工作要做,我们希望将这些非常耗时的操作由另外一个线程去执行,这个时候就 ...

  2. 一个动态扩展表格控件列和行的 jQuery 插件

    一个动态扩展表格控件列和行的 jQuery 插件 不过这并不影响使用鸭! 看这里:https://github.com/zhuwansu/table-ext.js 一个简单的示范 html <t ...

  3. GB国标编码的程序出现乱码

  4. JVM系列七(JIT 即时编译器).

    一.概述 即时编译器(Just In Time Compiler),也称为 JIT 编译器,它的主要工作是把热点代码编译成与本地平台相关的机器码,并进行各种层次的优化,从而提高代码执行的效率. 那么什 ...

  5. Webpack实战(六):如何优雅地运用样式CSS预处理

    上一篇文章中,我主要分享了<Webpack如何分离样式文件>CSS 预处理器是一个能让你通过预处理器自己独有的语法来生成CSS的程序,css预处理指的是在开发中我们经常会使用一些样式预编译 ...

  6. es7中数组如何判断元素是否存在

    const arr = [1,2,3,4,5,6] console.log(arr.includes(4)) //true

  7. MATLAB2017 下载及安装教程

    全文借鉴于软件安装管家 链接: https://pan.baidu.com/s/1-X1Hg35bDG1G1AX4MnHxnA 提取码: ri88 复制这段内容后打开百度网盘手机App,操作更方便哦 ...

  8. 单独立使用Django ORM

    一.常用的ORM框架简介 在Python下的ORM库不少,同样介绍类似的博文也不少,但是是我非常规的用法,顺便做做笔记.这里参考Python 常用的ORM框架简介文章列出几个, 这个几个我都使用过,但 ...

  9. Shiro自定义密码匹配认证

    项目集成shiro的时候,有写某个自定义类然后继承自AuthorizingRealm 并且重写实现了他的2个方法: 1.其中一个:认证回调 验证账户密码的 doGetAuthenticationInf ...

  10. Linux防火墙之iptables常用扩展匹配条件(一)

    上一篇博文讲了iptables的基本匹配条件和隐式匹配条件,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/12269717.html:今天在来说说iptabel ...