There is a difference between the session and the servlet context. I think that you are confuse because you are using the session object to get the servlet context. Your data is clearly set in the servlet context in this example. Even if you are using web services, you will have a servlet context provided by the servlet container.
Now I don't know which technologies you are using, but there's many other ways to make static data available to all your web services. For example, using a cache mechanism might be a better solution for data that is stored in the database...
A Servlet Session is a very different thing from a Servlet Context.
An HttpSession is a mechanism used to simulate and maintain a continuous user Session between a Web Browser and Web Application, largely managed by the Servlet Container. The HTTP protocol is stateless, it is essentially a request-response scheme, so Servlet Sessions are maintained by passing a unique HTTP cookie value for each request, or by dynamically including an identifier in Servlet URLs, known as URL-rewriting.
A ServletContext object represents the overall configuration of the Servlet Container and has several methods to get configuration parameters, exchange data amongst Servlets, forward requests and load resources. The Servlet Context is usually obtained indirectly through the ServletConfig object, passed to a Servlet's init(ServletConfig) method, or from the Servlet getServletConfig() method.
Javadoc definition for ServletContext :
Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)
EDIT
To get the ServletContext
object in a Spring
application, use the @Autowired
annotation. Note that the object should be managed by the Spring container, it will be the case if you are using controllers for you REST
services.
@Autowired
ServletContext servletContext;
Here an example :
@Controller
@RequestMapping("/foo")
public class RESTController {
@Autowired
ServletContext servletContext;
@ResponseBody
@RequestMapping(value="/bar", method = RequestMethod.GET)
public List<Roles> getRoles() {
return servletContext.getAttribute(MyAppConstants.ROLES);
}
}