Session state using guice - java

I've some session scoped state. First idea to hold it was session scoped servlets. So I bind my servlet like this
bind(Foo.class).in(ServletScopes.SESSION);
But I get an exception
javax.servlet.ServletException: Servlets must be bound as singletons. Key[type=Foo, annotation=[none]] was not bound in singleton scope.
So servlets can't have scope from ServletScopes? Whats the right way to deal with session state (yeah, of course it's better to write state less servlets/classes/applications)?

From my understanding you can bind whatever you want to the session scope, the problem is that in your example Foo seems to be an subclass of Servlet, and Servlets must be bound in Singleton scope.
To resolve this, just bind your state (called Bar) in session scope and give your Foo constructor a Provider<Bar> argument (which will be filled in by Guice) so you can access the session-scoped state from the singleton-scoped Foo Servlet.

servlets are not created by Guice, but by the servlet container. And they are singletons : only one instance is created by the servlet container to serve all the requests of all the clients.
So binding them to session scope has no sense : Guice can not create one different servlet instance per session.
A servlet should always be stateless (i.e. its state should be global to all the clients, and be accessed in a thread-safe way)

Related

SpringBoot Single Page Application Concurrency

I have copied a sample Spring Boot SPA. I want to understand, what happens if multiple people use the web page via the URL. Does Java create an instance of the web application per call? Memory resources are not shared, right, i.e. if there is a list object appended to, each user sees their own list?
The default scope for a spring-boot bean is a singleton. Assuming your bean is not managing state you should be fine with the default behavior:
https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html
4.4.1 The singleton scope
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with
an id or ids matching that bean definition will result in that one
specific bean instance being returned by the Spring container.
To put it another way, when you define a bean definition and it is
scoped as a singleton, then the Spring IoC container will create
exactly one instance of the object defined by that bean definition.
This single instance will be stored in a cache of such singleton
beans, and all subsequent requests and references for that named bean
will result in the cached object being returned.
Now if you are using a bean that's stateful and want a new bean used per request, you can define the scope of that bean to be prototype:
4.4.2 The prototype scope
The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a
request for that specific bean is made (that is, it is injected into
another bean or it is requested via a programmatic getBean() method
call on the container). As a rule of thumb, you should use the
prototype scope for all beans that are stateful, while the singleton
scope should be used for stateless beans.
Spring resources like #Service and #Repository and #RestController are stateless singletons. Only a single instance is created to serve the application.
Your implementation of the list at scope level will determine whether or not it is shared. If you define the List in the Controller, as in your example, then every user will have access to the same list. You can use multiple browsers to see that the list is shared. Based on the example, this is fine, as getting "all" should really mean getting all.
If you wanted each user to have their own list, you would have to implement some sort of Session or back-end process to associate each individual user with their own list.
This isn't shared-nothing like PHP or Rails. Java is so slow starting up that firing up a new instance of the application for every request isn't an option.
Check out the spring-boot sample application source code, there's a main method on the SpringbootJQueryAjaxClientApplication class, like this:
public static void main(String[] args) {
SpringApplication.run(SpringBootJQueryAjaxClientApplication.class, args);
}
this is the main method like for any Java program, what happens here is it starts the self-hosted servlet container and installs the application into it, then waits for http requests.
It is one process, where every request is served by a thread, so memory is shared. Spring components like com.javasampleapproach.jqueryajax.controller.RestWebController (scoped as singleton by default) are instantiated once in the web application, and every request calls methods on the same instance.

What ia use of request scoped beans?

I want to understand what is use of request scoped beans in spring? I know it lives only till the request is alive. But I can't think of any practical use.
It is what it is, you get a bean scoped for the current request. That means that whenever you ask the spring context to give you a specific bean which is request scoped, you will get different instances for different requests. If you ask for the same bean twice in the same request, you'll get the same instance as you would expect.
Please note that in order to use request scoped beans in a singleton bean (the default bean scope in Spring), you will need a scoped proxy. That means, you'll need to use a singleton proxy instance in your singleton beans that will actually delegate all method invocations to the per-request scoped instances of that type.
See this answer on spring scoped proxy bean for a very nice and detailed explanation.

Why can't stateful beans be exposed as webservices?

I have been reading about Stateful and Stateless session beans and came across a sentence that states that:
Stateful session beans cannot be exposed as web services.
Can anyone elaborate why ?
Every Stateful bean instance located in the EJB Container has an unique object identity.
From spec.: 3.4.7.1 Stateful Session Beans
A stateful session object has a unique identity that is assigned by the container at the time the object is created.
In order to use a Stateful bean, the client code needs to get a Stateful reference from the EJB Container.
This reference has to be used to make every future request.
Due to the reference object knows the identity associated to the stateful bean, you can be sure that all requests that participate in the "conversation" will be resolved for the same instance bean. This means that the Client has an important role in achieving the stateful behavior.
The SOAP protocol doesn't provide a way that allow to store in a web service client this identity, therefore, if the client doesn't know which stateful instance has the conversational state, every request will be processed by different ejb (such as the case of stateless).
This is because, typically, state does not required to maintained across web service client calls. Moreover, SOAP-based web services are inherently stateless in nature. If you need to maintain state across web service calls, stateless beans can be used to persist state (although this degrade application performance)

.java terms and random words clarification

Im really new to java, jsf, jsp, and I need to learn how it works quickly. So the website Im using to practise has some terms etc that I dont know what they mean and Im hoping somebody can explain what they mean and how/what they are used for:)
Requestscoped
Applicationscoped
Sessionscoped
EntityManager
and could someone walk me through what these lines do?
#RequestScoped
public class Dao {
#DataRepository
#Inject
private EntityManager entityManager;
First of all, in Java (5 and higher), "things" starting with a # (e.g. #Deprecated) are called annotations.
Annotations provide data about a
program that is not part of the
program itself. They have no direct
effect on the operation of the code
they annotate.
Your JavaBeans needs to be configured to a scope if you want to use it in JSF (Definitions can be found here).
#RequestScoped: Objects with this scope are visible from the start of the request until the end
of the request. Request scope starts at the beginning of a request and ends when the
response has been sent to the client. If the request is forwarded, the objects are visible
in the forwarded page, because that page is still part of the same request/response
cycle. Objects with request scope can use other objects with none, request, session,
or application scope. If you have to think it in terms of servlet, the managed bean is stored in the HttpServletRequest until the end of the request (when the response is sent to the client). After that, the bean no longer exists in the request.
#SessionScoped: An object with session scope is visible for any request/response cycle that
belongs to a session. Objects with this scope have their state persisted between
requests and last until the object or the session is invalidated. Objects with session
scope can use other objects with none, session, or application scope. Basically, these objects are stored in a HttpSession (refer to Servlets again). Each session has a session ID (known as JSESSIONID) that the bean is associated with.
ApplicationScoped: An object with application scope is visible in all request/response cycles
for all clients using the application, for as long as the application is active. In terms of Servlet, this could be, managed bean stored in a ServletConfig.
#NoneScoped: Objects with this scope are not visible in any JSF page. When used in the configuration file, they indicate managed beans that are used by other managed beans in the application. Objects with none scope can use other objects with none scope.
For EntityManager, this is associated with persistence context. It is used to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities. For more, refer to the JPA (Java Persistence API) Specification, or Hibernate.
#Inject, means that the instance is injectable. They follow the infamous crase word of Depency Injection or Inversion of Control (IOC). What this basically mean, is that when the resource (in your case EntityManager entityManager is needed, the JEE container instantiates the resource for you (without you needed to instantiate it directly through e.g. a constructor, etc.).
I have no clue what #DataRepository means. Never seen it before.
I hope this helps you.
These terms are usually associated with a dependency injection framework like guice and not with java in particular.
http://code.google.com/p/google-guice/wiki/Scopes describes the various scopes that are built into guice.
By default, Guice returns a new instance each time it supplies a value. This behaviour is configurable via scopes. Scopes allow you to reuse instances: for the lifetime of an application (#Singleton), a session (#SessionScoped), or a request (#RequestScoped). Guice includes a servlet extension that defines scopes for web apps. Custom scopes can be written for other types of applications.

How to access to the 'Session' of an EJB?

How to get the session object of an EJB session-bean like session object in JSP(web layer)?
Because I want to add an attribute to the session and use it later in its process.
Regards
In the web layer you get the session with
request.getSession()
This returns the session object tied to this request. Here you can store session specific attributes you can reuse on subsequent requests.
In the EJB layes you have completely different session objects which have nothing to do with the session above. There are Stateless Session Beans and Stateful Session Beans. Stateful session beans can also keep state over multiple requests however they are very tricky to work with and are only useful for a very limited set of use-cases. Stateless Session Beans do not keep (outside detectable) state between calls, so are useless to store attribtes you want to reuse later, unless you store them in a persistence layer or a cache.
In most cases the easiest to work is to keep the conversation state in the request session object and pass the attribute you want to reuse later from the web layer to a stateless service bean as a parameter.

Categories