JSON拦截器配置文件全指南:从基础到实践
JSON拦截器配置文件全指南:从基础到实践
在现代化的Web开发中,JSON作为轻量级的数据交换格式,已成为前后端通信的“事实标准”,为了保障数据安全、统一处理响应格式或实现日志记录等功能,JSON拦截器的配置显得尤为重要,本文将详细介绍JSON拦截器的配置文件方法,从基础概念到具体实践,帮助开发者快速这一技能。
什么是JSON拦截器?
JSON拦截器(Interceptor)是一种中间件机制,位于客户端请求与服务器业务逻辑之间,用于拦截和处理HTTP请求/响应,当数据以JSON格式传输时,拦截器可以:
- 修改请求/响应数据:如统一添加token、过滤敏感字段;
- 实现日志记录:记录请求参数、响应时间等关键信息;
- 异常处理:捕获JSON解析错误,返回统一格式的错误提示;
- 权限校验:验证请求头中的JSON Token是否有效。
配置文件则是实现拦截器功能的核心载体,通过定义规则让拦截器“知道”何时触发、如何处理数据。
常见框架中的JSON拦截器配置
不同开发框架对拦截器的配置方式略有差异,本文以主流的Spring Boot(Java)、Express(Node.js)和Django(Python)为例,讲解配置文件的编写方法。
(一)Spring Boot:通过Interceptor接口与配置类
Spring Boot中,拦截器需实现HandlerInterceptor接口,并通过WebMvcConfigurer注册,配置文件通常以application.yml或application.properties形式存在,用于定义拦截路径等规则。
实现拦截器逻辑
创建一个自定义拦截器类,处理JSON相关的请求/响应:
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class JsonInterceptor implements HandlerInterceptor {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 1. 拦截JSON请求:检查Content-Type是否为application/json
if ("application/json".equals(request.getContentType())) {
System.out.println("拦截到JSON请求: " + request.getRequestURI());
// 示例:从请求头中提取token并校验
String token = request.getHeader("Authorization");
if (token == null || !token.startsWith("Bearer ")) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
objectMapper.writeValue(response.getWriter(),
"{\"code\":401, \"message\":\"未授权\"}");
return false; // 拦截请求,不继续执行
}
}
return true; // 放行请求
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 2. 处理JSON响应:统一修改响应格式
if ("application/json".equals(response.getContentType())) {
System.out.println("处理JSON响应: " + request.getRequestURI());
// 示例:为响应添加统一时间戳
Object originalResponse = request.getAttribute("originalResponse");
if (originalResponse != null) {
String jsonResponse = objectMapper.writeValueAsString(originalResponse);
String modifiedResponse = "{\"timestamp\":" + System.currentTimeMillis() +
", \"data\":" + jsonResponse + "}";
response.getWriter().write(modifiedResponse);
}
}
}
}
配置拦截器路径
通过WebMvcConfigurer配置类,定义拦截器生效的URL模式(如/api/**)和排除路径(如/api/public/**):
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private JsonInterceptor jsonInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jsonInterceptor)
.addPathPatterns("/api/**") // 拦截所有/api路径下的请求
.excludePathPatterns("/api/public/**") // 排除/api/public/**路径
.order(1); // 设置拦截器顺序
}
}
结合application.yml配置
如果拦截器需要读取外部配置(如白名单路径),可在application.yml中定义:
interceptor:
json:
exclude-paths:
- /api/public/**
- /api/health
然后在拦截器中通过@Value注入:
@Value("${interceptor.json.exclude-paths}")
private List<String> excludePaths;
(二)Express:通过app.use()与中间件配置
Express是Node.js的轻量级Web框架,其拦截器本质是“中间件”(Middleware),配置方式灵活,可直接在代码中定义,也可通过外部配置文件(如config.json)管理规则。
编写JSON拦截中间件
创建jsonInterceptor.js,处理JSON请求的校验与响应修改:
const jwt = require('jsonwebtoken');
const jsonInterceptor = (req, res, next) => {
// 1. 拦截JSON请求:检查Content-Type
if (req.is('application/json')) {
console.log('拦截到JSON请求:', req.originalUrl);
// 示例:校验JSON Token
const token = req.headers['authorization'];
if (!token || !token.startsWith('Bearer ')) {
return res.status(401).json({
code: 401,
message: '未授权'
});
}
// 解析token(假设密钥为'secret')
try {
const decoded = jwt.verify(token.split(' ')[1], 'secret');
req.user = decoded; // 将用户信息附加到请求对象
} catch (err) {
return res.status(401).json({
code: 401,
message: 'Token无效'
});
}
}
// 2. 处理JSON响应:统一格式
const originalSend = res.json;
res.json = function(data) {
const modifiedData = {
timestamp: Date.now(),
data: data
};
originalSend.call(this, modifiedData);
};
next(); // 放行请求
};
module.exports = jsonInterceptor;
应用中间件与配置路径
在Express应用中,通过app.use()注册中间件,并定义路径规则:
const express = require('express');
const jsonInterceptor = require('./middlewares/jsonInterceptor');
const app = express();
// 配置拦截器:拦截所有/api路径,排除/api/public
app.use('/api', jsonInterceptor);
app.use('/api/public', (req, res, next) => next()); // 排除路径
// 示例路由
app.post('/api/user', (req, res) => {
res.json({ name: '张三' });
});
app.listen(3000, () => {
console.log('服务运行在 http://localhost:3000');
});
外部配置文件(可选)
如果需要灵活管理拦截规则,可创建config.json:
{
"interceptor": {
"json": {
"paths": ["/api"],
"excludePaths": ["/api/public", "/api/health"]
}
}
}
在应用中读取配置:
const config = require('./config.json');
const paths = config.interceptor.json.paths;
const excludePaths = config.interceptor.json.excludePaths;
paths.forEach(path => {
app.use(path, jsonInterceptor);
});
excludePaths.forEach(path => {
app.use(path, (req, res, next) => next());
});
(三)Django:通过middleware类与settings.py配置
Django的拦截器通过“中间件”(Middleware)实现,配置文件为settings.py,需自定义中间件类并添加到MIDDLEWARE列表中。
自定义JSON中间件类
创建middleware/json_interceptor.py,实现JSON请求/响应的处理逻辑:
from django.http import JsonResponse
import json
import time
class JsonInterceptorMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# 1. 拦截JSON请求:检查Content-Type
if request.content_type == 'application/json':
print(f"拦截到JSON请求: {request.path}")
# 示例:校验Token(从请求头获取)
token = request.headers.get('Authorization')
if not token or not token.startswith('Bearer '):
return JsonResponse(
{'code': 401, 'message': '未授权'},
status=401
)
# 解析JSON请求体(可选)
try:
request.json_data = json.loads(request.body)
except json.JSON


还没有评论,来说两句吧...