Home > Software engineering >  Variable for Controller.but I like to set it from HttpInterceptor. How do I achieve this?
Variable for Controller.but I like to set it from HttpInterceptor. How do I achieve this?

Time:03-26

I am building SpringBoot Application.

I like to set a variable for the SpringBoot application. this variable will 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.

Do you have any Idea How I achieve this?

CodePudding user response:

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

}

CodePudding user response:

  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
  • Related