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

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. js点击回到顶部2

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>点 ...

  2. ironic驱动-IMPITool

    概述 IMPITool驱动是通过ipmitool工具来管理部署节点的,目前主要有两个驱动: agent_ipmitool pxe_ipmitool 配置驱动 要修改ironic支持的驱动需要修改配置文 ...

  3. 安装pytorch0.4.0

    参考了官网https://pytorch.org/previous-versions/中的说明 (jj1env) [ji@dev down_python0.4.0]$ pip install http ...

  4. 【搜索】传感器 @upcexam6023

    时间限制: 1 Sec 内存限制: 128 MB 题目描述 SR最近新买了一款电子桌游 这个玩具内部是M个围成一圈的传感器.每个传感器都有开和关两种工作状态,分别用1和0表示.显然,从不同的位置触发沿 ...

  5. ESP8266 NOOS SDK libat.a Functions

    at_baseCmd.o custom_infoat_baseCmd.o at_exeCmdNullat_baseCmd.o at_setupCmdEat_baseCmd.o at_exeCmdRst ...

  6. scipy.stats与统计学:4个概率分布:N,chi2,F,t

    scipy.stats与统计学:4个概率分布:N,chi2,F,t   四个常用分布的概率密度函数.分布函数.期望.分位数.以及期望方差标准差中位数原点矩: 1,正态分布: from scipy.st ...

  7. SQLAlchemy——获取某列为空的数据

    session.query(StockAllInfo).filter( StockAllInfo.ts_code == tsCode and StockAllInfo.py_code==None).a ...

  8. Android application捕获崩溃异常

    Java代码 .收集所有 avtivity 用于彻底退出应用 .捕获崩溃异常,保存错误日志,并重启应用 , intent, , restartIntent); // 关闭当前应用 finishAllA ...

  9. InfluxDB添加新服务

    操作系统 : CentOS7.3.1611_x64 go语言版本:1.8.3 linux/amd64 InfluxDB版本:1.1.0 这里以添加 syncd 服务为例记录下InfluxDB添加新服务 ...

  10. 安装了 R2 Integration Servic 之后,SQL Server 2008 Management Studio报错

    问题产生 IM数据库服务器未安装Integration Servic,影响备份.在安装了安装了 SQL Server 2008 R2 Integration Servic 之后,SQL Server ...