首页 > 解决方案 > 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...
    }
}

标签: springspring-boot

解决方案


最简单的方法是使用过滤器,如下所示:

@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);
            }
        };
    }

}

推荐阅读