Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
    }
}
like image 905
nami20 Avatar asked Mar 31 '26 20:03

nami20


1 Answers

The easiest way would be to use a Filter as follows:

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

}
like image 70
codependent Avatar answered Apr 03 '26 10:04

codependent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!