在前面代码基础上进行改造;

1.SpringBoot常用注解

@SpringBootApplication :指定SpringBoot项目启动的入口,是一个复合注解,由@Configuration、@EnableAutoConfiguration、@ComponentScan三个注解。

@Configuration:表示将该类作用springboot配置文件类。

@EnableAutoConfiguration:表示程序启动时,自动加载springboot默认的配置。

@ComponentScan:表示程序启动是,自动扫描当前包及子包下所有类。

@SpringBootConfiguration:说明这是一个配置文件类,就像xml配置文件,而现在是用java配置文件。

@Value:通过这个注解可以来读取.properties或.yml中配置的属性。

@Bean:这个注解是方法级别上的注解,主要添加在 @Configuration 或 

@SpringBootConfiguration 注解的类,有时也可以添加在 。

@Component 注解的类。它的作用是定义一个Bean。

2.拦截器

先定义拦截器:

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 拦截器
* @author XIHONGLEI
* @date 2018-11-02
*/
public class ApiInterceptor implements HandlerInterceptor { /**
* 请求之前访问
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("请求之前拦截...");
return true;
} /**
* 请求时访问
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("请求中拦截...");
} /**
* 请求完成后访问
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println("请求完成后拦截...");
}
}

再将自定义拦截器添加注册进系统

import com.hello.filter.ApiInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /**
* 配置类
* @author XIHONGLEI
* @date 2018-10-31
*/
@SpringBootConfiguration
public class WebConfig extends WebMvcConfigurationSupport { @Override
protected void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
// 将 ApiInterceptor 拦截器类添加进去
registry.addInterceptor(new ApiInterceptor());
}

看效果:

3.异常处理

创建异常处理类->加入@Aspect、@Component 注解->对请求链接进行拦截->发生异常之后的异常处理

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter; /**
* 异常拦截处理
*
* @author XIHONGLEI
* @date 2018-11-02
*/
@Aspect
@Component
public class WebExceptionAspect {
//凡是注解了RequestMapping的方法都被拦截
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
private void webPointcut() {
System.out.println("请求被拦截...");
} /**
* 拦截web层异常,记录异常日志,并返回友好信息到前端
* 目前只拦截Exception,是否要拦截Error需再做考虑
* @param e 异常对象
*/
@AfterThrowing(pointcut = "webPointcut()", throwing = "e")
public void handleThrowing(Exception e) {
System.out.println("出现异常:");
e.printStackTrace();
// 输出错误提示到浏览器
writeContent("您请求的链接出现异常,请重试!");
} /**
* 将内容输出到浏览器
* @param content 输出内容
*/
private void writeContent(String content) {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "text/plain;charset=UTF-8");
response.setHeader("icop-content-type", "exception");
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
writer.print(content);
writer.flush();
writer.close();
}
}

SpringBoot系统列 4 - 常用注解、拦截器、异常处理的更多相关文章

  1. springboot + 注解 + 拦截器 + JWT 实现角色权限控制

    1.关于JWT,参考: (1)10分钟了解JSON Web令牌(JWT) (2)认识JWT (3)基于jwt的token验证 2.JWT的JAVA实现 Java中对JWT的支持可以考虑使用JJWT开源 ...

  2. springboot + redis + 注解 + 拦截器 实现接口幂等性校验

    一.概念 幂等性, 通俗的说就是一个接口, 多次发起同一个请求, 必须保证操作只能执行一次 比如: 订单接口, 不能多次创建订单 支付接口, 重复支付同一笔订单只能扣一次钱 支付宝回调接口, 可能会多 ...

  3. Springboot + redis + 注解 + 拦截器来实现接口幂等性校验

    Springboot + redis + 注解 + 拦截器来实现接口幂等性校验   1. SpringBoot 整合篇 2. 手写一套迷你版HTTP服务器 3. 记住:永远不要在MySQL中使用UTF ...

  4. springBoot(6)---过滤器,监听器,拦截器

    过滤器,监听器,拦截器 一.理解它们 看里十几篇博客,总算有点小明白,总的来讲,两张图可以让我看明白点. 通过两幅图我们可以理解拦截器和过滤器的特点 1.过滤器 过滤器是在请求进入tomcat容器后, ...

  5. SpringBoot系统列 2 - 配置文件,多环境配置(dev,qa,online)

    实现项目的多环境配置的方法有很多,比如通过在Pom.xml中配置profiles(最常见) 然后在Install项目打War包的时候,根据需求打不同环境的包,如图: 这种配置多环境的方法在SSM框架中 ...

  6. SpringBoot系统列 1 - HelloWorld!

    学习SpringBoot系统列之HelloWorld! 1.新建一个Maven项目 2.添加POM配置 <parent> <groupId>org.springframewor ...

  7. Spring MVC 方法注解拦截器

    应用场景,在方法级别对本次调用进行鉴权,如api接口中有个用户唯一标示accessToken,对于有accessToken的每次请求可以在方法加一个拦截器,获得本次请求的用户,存放到request或者 ...

  8. springboot设置过滤器、监听器、拦截器

    其实这篇文章算不上是springboot的东西,我们在spring普通项目中也是可以直接使用的 设置过滤器: 以前在普通项目中我们要在web.xml中进行filter的配置,但是只从servlet 3 ...

  9. springboot配置监听器、过滤器和拦截器

    监听器:listener是servlet规范中定义的一种特殊类.用于监听servletContext.HttpSession和servletRequest等域对象的创建和销毁事件.监听域对象的属性发生 ...

随机推荐

  1. 考前停课集训 Day3 匪

    Day3——作死不可活的一天 Day3 今天下午才考 晚上时间少 下午网每断 因此我是PY的 然后被抓了 成绩做0分处理. 是啊,我只会抄题解. 其他什么都不会. 一无是处. 真的. 真实能力:ran ...

  2. yii2 getter

    GridView 表格多余内容显示 ... 1.直接在 GridView 中使用匿名函数书写,这种适合单个使用 <?= GridView::widget([ 'dataProvider' =&g ...

  3. Java WebSocket 线程安全的保证

    Java WebSocket线程安全基于3点: 1 在新的客户端连接时,WebSocket容器会创建一个新的端点实例,对应的会话实例表示从唯一的客户端到该端点实例的唯一连接. 2 每个WebSocke ...

  4. Incorrect username or password ( access token )解决

    Q:Git提交时,给出提示Incorrect username or password ( access token ) K: 此处是用户名或者密码有误,建议解决方法两种.具体看哪一种可行,可试. 第 ...

  5. 学习Struts--Chap03:struts.xml常用配置(基础)

    1.package属性 name:包名 用来唯一的指定一个package.package可以扩展,当一个package扩展自 另一个package时该package会在本身配置的基础上加入扩展的pac ...

  6. RS485 VS 20mA 电流环

    RS485采用差分信号负逻辑,+2V-+6V表示“0”,- 6V-- 2V表示“1”.RS485有两线制和四线制两种接线,四线制只能实现点对点的通信方式,现很少采用,现在多采用的是两线制接线方式,这种 ...

  7. GMA Round 1 新年祝福

    传送门 新年祝福 15个人聚集在一起,新年到来,他们每个人写下了一句新年祝福.大家把祝福收集起来,然后重新分回去.如果一个人拿到了自己写的祝福,他就会觉得很没有意思,因为得不到别人的祝福.要避免这种尴 ...

  8. poj3253 Fence Repair(贪心+哈夫曼 经典)

    https://vjudge.net/problem/POJ-3253 很经典的题,运用哈夫曼思想,想想很有道理!! 具体实现还是有点绕人,最后被long long卡了一下,看数据大小的时候单纯相乘了 ...

  9. fzu1062 洗牌问题(思路模拟)

    http://acm.fzu.edu.cn/problem.php?pid=1062 一开始想暴力找规律,没看出来..然后开始推,推测根据1再次返回第一个的时候顺序也复原,然后想以此推导出一个规律公式 ...

  10. vim8.0模式详解

    pattern pattern.txt For Vim version 8.0. 最近更新: 2017年8月 VIM 参考手册 by Bram Moolenaar 译者: lang2 http://v ...