If I correctly understand, there are different questions :
- how to access the variables from JSP : user3218114 has allready answered this part, but if you create the variable outside of the JSP, you simply access them with
${bean.property
}. Methods are harder to call (again see referenced answer), but if you use servlets, JSP should only be views and you should think twice before calling methods in a JSP.
- how to access the variables from other beans : you can use Dependancy Injection if you use a true Java EE container (not Tomcat ...) or Spring, and unfortunately there will be slightly difference in the way to use it. But it is really a question on its own and I will not develop this further even if it is to considere for any serious developpement
how to access variables from servlets : I only know one way scope.getAttribute("name"), with scope in Request, Session, ServletContext, that return an Object that need to be casted before use ... but you can always use private methods or static utility methods to hide the details, for example :
public class MyUtil {
public MyObject getMyObject(ServletRequest request) {
return (MyObject) request.getAttribute("my_object");
}
}
and later in your serlvets or filters you simply call MyUtil.getMyObject(request)
- how to initialize those scoped variables : Requests and Session scoped variables are generally created in servlets or filters and are simply put as attribute in their scope either directly or through an utility methode like above. Application level beans (ServletContext scope) are generally created outside any request and should be initialized in a
ServletContextListener
. For special use cases, you can also use a HttpSessionListener
to put beans in session context outside of a Servlet.
Edit : just a point about serialization
Request scoped bean do not need to be serializable. For Session or ServletContext scoped beans, the answer is more subtle : if you want your application to be distributable (ie be deployed on a cluster of servers) all attributes put in Session or ServletContext should be Serializable. Nothing forces you to to so, and you will have no errors if you do not, but a container is allowed to serialize a session and all non Serializable attributes are simply thrown away (with a warning for Tomcat). An even in non distributed environments, I noticed that Tomcat serializes sessions when stopping and undeploying a web application, and restores them on next deploy.
So my advice is : all Session or ServletContext scoped beans should be Serializable (and I wrote should not must ...)