Issue
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?
Solution
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"));
}
}
Answered By - GeertPt
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)