Java – is the localecontextholder secure in the service layer
According to the official documents, the localecontextholder is:
So it's related to the current thread, but it's about the thread or the thread of the current request
If it's a stupid question, please apologize. I'm not a localecontextholder. It's safe not to bind to HTTP session or other things so that it can be used in any service layer class
Solution
If you look at the source code of the localecontextholder, you will notice that it has a ThreadLocal variable (actually two)
private static final ThreadLocal<LocaleContext> localeContextHolder = new NamedThreadLocal<LocaleContext>("Locale context");
You can read the contents of ThreadLocal, but for our purposes, please treat it as a data structure that maps the ID of the currently executing thread to the object localcontext of its generic type
The servlet container has a thread pool for processing client requests When the request enters, it extracts one of the threads and executes the service () method of your servlet Using spring, this will cause the dispatcher servlet to execute and call the handler method of @ controller All this happens in the original thread selected by the servlet container
So when your @ service class' method is called, you are still in the same thread
ThreadLocal in localecontextholder is set() at some early time in request processing. In frameworkservlet (which is the parent type of dispatcherservlet), initcontextholders() is called by processrequest() in each doget(), dopost(), etc method. Locale is built from HttpServletRequest using its getlocale () method