spring - How to create a middleware on controller level in spring boot java?
问题描述
I want to create a middleware when request comes on controller like we did in express Nodejs.
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
api.post('/', function(req,res) {
// enter code here...
})
Is it possible in spring boot doing the same functionality Like
@RestController
@RequestMapping("/api")
private class TestApiMiddleware {
// middleware...
@RequestMapping(value = "/save", method = RequestMethod.POST)
protected list() throws Exception {
// code...
}
}
解决方案
最简单的方法是使用过滤器,如下所示:
@Configuration
public class FilterConfiguration {
@Bean
public Filter loggerFilter() {
return new Filter() {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.info("LOGGED");
chain.doFilter(request, response);
}
};
}
}
推荐阅读
- windows - Microsoft Store 上的 AB 测试
- python - Visual Studio 2019 Python 2.7 调试只打印第一个打印语句
- python - Python3 tkinter 批处理构建按钮
- python - 是否有 python 函数来扩展日期(类似于电源查询中的 List.Dates)?
- spring-integration - 将 spring 集成版本从 4.3.12 升级到 5.2.5 后,在 sftp outbound-gateway 中出现“没有此类文件”异常
- .htaccess - 有没有办法重写 url 中的哈希字符 - htaccess
- long-integer - IAR 不能长线(80th)
- java - java.io.IOException:监听失败:EINVAL(无效参数)尝试保存到没有非法字符的公共下载文件夹时
- typescript - 如何在 Nestjs 中通过条件激活组件
- excel - 一次性删除空白、空、零