Controlling scope in Java EE projects

2019-09-08 06:27发布

问题:

What is the method of controlling scope in Java EE projects. I'm reading about session, request, application scope and that certain beans should be limited to one or the other. How is this generally done? Is it by what type of project the bean is created in, a special annotation, or some other method? In my experience I've noticed that when outside of the same package none of my beans, servlets or DAO's have access to each other unless I inject or import the related class.

回答1:

I think you are mixing things. The scopes you listed are for JSF backing beans and are generally related to the HTTP session or request. EJB-s has no scope in this context. To use them they have to be injected using DI annotations (or alternatively via JNDI context lookup).



回答2:

Scope refers to how long a variable lives and is available for use. Within a Java web app there are four scopes: Page, Request, Session and Application. For variables/objects that have Page scope, they exist only within the JSP page. Any object or variable that is created within a JSP has Page scope by default.

Request scope variables/objects live as long as the Request is valid-- remember that a request may span more than one JSP/Servlet.

Session scope objects live and are accessible via all across all Requests, JSPs and Servlets for the duration of a session. A 'session' is typically all the pages that a user views during a login session.

Application scope objects and variables are global in scope and are around as long as the application is running. They are accessible from all Requests, JSPs, Servlets, etc.



回答3:

You're confusing EE scope with class/package/etc. scope.

Objects can be exposed to JSP pages (or other view-layer technology) by putting them in one of the scopes you mention. It's not related to Java package/class visibility, but whether the object is available to the entire application, the current user's session, the current request, or the current page.

Application scope lives for the duration of the app. Session scope is specific to a particular user's "conversation" with the app--it's why we need a session cookie or URL re-writing (the jsessionid thing). Request scope lasts the duration of a user's specific request, and is also specific to a particular user. Page scope... honestly, I'm not sure how often its used.