'How to set a variable for Controller from HttpInterceptor? [closed]

I am building a Spring Boot application.

I like to set a variable for the Spring Boot application. This variable should be set in an HTTP interceptor. The reason I do this, this variable will store some ID, and this ID will be used in methods in every controller.

How can I achieve this?



Solution 1:[1]

You SET the variable in an HTTP interceptor? So it's not a unique global variable, it's an ID that is different for every request? That's what request attributes are for:

@Component
public class MyInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(request.getMethod().matches(RequestMethod.OPTIONS.name())) {
            return true;
        }
        request.setAttribute("MY_ID", generateId(...));
        return true;
    }


}

@Controller
public class SampleController {

    @RequestMapping(...)
    public String something(HttpServletRequest req, HttpServletResponse res){
        System.out.println( req.getAttribute("MY_ID"));
    }

}

Solution 2:[2]

  1. Pass it as JVM args and use it using System.getProperty.
  2. Use -Dspring-boot.run.arguments=--interceptor.enabled=true and keep a backup config in application.properties or using -Drun.arguments and access the property key directly in your interceptor

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GeertPt
Solution 2 Roopesh Payyanath