Reuse implemented business classes in a web applications - java

I have implemented my domain layer classes and i have used them in a java application.
Now i want to use same classes in a java web application,but i don't know how can i do it?
In the java application we make and run some objects in main(class and method) and use them while program is running.
for example an object that hold a collection of data that will be needed for all user requests.
My question is:
How can i create and hold such objects and data that should be available for all users and clients.

Place them in the application context. I.e. in a Servlet call getServletContext().setAttribute("name", yourCollection);
Then they can be retrieved by getServletContext().getAttribute("name")

You could create a singleton which represents the common application logic, initialising and cleaning up the common information and objects on web-app startup and shutdown.
All servkets can use the application singleton to retrieve and store.
To initialise and cleanup on web-app startup and shutdown you can define an administrative servlet which has the load-on-startup flag set in the deployment descriptor web.xml managing the application singleton from the init() and destroy() methods.

Related

Life cycle management of servlet when SingleThreadModel is used

According to the java docs, it says that If SingleThreadModel is used there are two ways a servlet instance will be created and used
1. Create one servlet instance and make the service() method synchronized and thus allow only one thread to execute the service method.
2. Create a pool of servlets and serve the request by using one servlet instance from the pool for each request.
THe question which I want to ask is I have also read a new Servlet instance is created and destroyed for every request. Now which one is correct
Here's what the spec says (version 3.0, section 2.2):
For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.
In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per Java Virtual Machine (JVMTM)1. However, if the servlet in a distributable application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each JVM of the container.
Note that you should really not use the single thread model. Just make sure your servlet is thread-sae. A servlet is typically stateless, so you don't have anything to do to make it thread-safe.
From the docs for SingleThreadModel:
Ensures that servlets handle only one request at a time
This is in essence a way to make non thread-safe servlet code work. Note that the container is free to choose any of the two implementations to adhere to the spec:
Create a single instance of the servlet and ensure that it handles only one request at a time
Create a pool of servlet instances and hand over a request to an available servlet instance.

ServletContext parameters: are they per instance or per server?

I have a tomcat server running a webapp. In the webapp's startup, I'm setting few context parameters using an implemented class for interface ServletContextListener. The parameter that I am initializing here are a couple of connection objects for a database running on a different machine.
The doubt that i have is whether the connection objects that I created here are one for each instance (since tomcat creates one instance per client request), or one for the entire webapp itself?.
If it is one per webapp, then can the server handle large simultaneous requests (in the order of thousand request per second) to perform the CRUD operations on the database?.
ServletContext is created one per webApp. The server reads the web.xml file from the web app and creates a ServletContext based on the configuration you provide on web.xml. Once created it is shared between the components of the web app. If you have multiple webapp installed on your server, you will have multiple ServletContext - each for the web app.
For reference please have a look here
A webapp has only one instance of ServletContext and the atributes in ServletContext are application scoped.
Regarding you database connection, it's better to use connection pooling (DataSource) instead of adding Connection objects as attributes in ServletContext.
Not sure if you mean this but the requests are handled by Servlets and not ServletContext.
If your setting an attribute on the ServletContext the attribute will be scoped for the entire application.
From the Java EE 7 Spec:
There is one instance object of the ServletContext interface
associated with each Web application deployed into a container.
only one ServletContext is loaded irrespective of the number of requests made.
This is even the advantage of servlets over CGI.
Hope it helps.

When exactly a web container initialize a servlet?

When exactly a web container initialize a servlet?
Is it guaranteed that it does it at web container start up time?
Thanks.
No, it's not. First, the webapp itself is not guaranteed to be started when the container starts (that depends on the specific container configuration). And even if the webapp is started, the specification says:
Servlets are initialized either lazily at request processing time or eagerly during deployment. In the latter case, they are initialized in the order indicated by their load-on-startup elements.
When exactly a web container initialize a servlet?
Either at the time of loading the web application or on the first request to the servlet. This is configurable in web.xml using load-on-startup flag
Is it guaranteed that it does it at web container start up time?
Nothing is guranteed when it comes to the container. It depends how the contianer is written .The only way to request the container is through configurable param load-on-startup in in web.xml.
Depends on how you are defining and configuring your servlet.
You might find this clearly in docs
Initializing a Servlet
After the web container loads and instantiates the servlet class and before it delivers requests from clients, the web container initializes the servlet. To customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities, you override the init method of the Servlet interface. A servlet that cannot complete its initialization process should throw UnavailableException.
If you want to participate in that process ovveride init method of the Servlet interface and do the required stuff there.

How to keep object instantiated between multiple requests with Java (Glassfish) SOAP Requests

I have done a lot of looking around on this topic but all I could find related to database connections etc.
I'm building a web service which loads a Shapefile and uses the GeoTools library to do some funky location based stuff. What I'd like to do is load the Shapefile once, get all the 'Features' in memory for the Shapefile, and then just be able to check against that collection each time - note there are actually many shapefiles loaded now.
I've wrapped my Geo-based stuff in a class, with it loading the shapefiles into a collection when the class is instantiated. My #WebService class checks to see if myGeoClass is instantiated, else it creates it and loads the files into memory. These files never change, so I'd like to keep the same instance of the object between multiple requests, but I've added some traces in and it seems to be creating a new instance in with every request.
Is there a way to keep the single instance in memory, shared across all requests?
Cheers!
At the very least you could use a static variable.
If it is a web app , then you can set it as an attribute of the ServletContext.
If you are using Java EE 6 then you can define your class as a managed bean #ApplicationScoped or a Singleton

An always-running thread in Servelts

I need to built a thread/process that is always running, and can be queried through other servelts and JSP pages...
This thread/process will be dealing with large files, so it will cache file blocks to reduce file accesses (plus some other processing)...
So, that thread/process will be loaded and waiting for any queries coming, to answer... as long as the server is running.
I though about making a static class common between all the servelt classes, but I found out that will not work (tomcat deals with each new servelt as a totally new program)
So what are the other options I can try??
I think you have two options:
Use the ServletContext to access application-wide scope objects.
Use a more sophisticated solution, such as ehcache to put your data in memory.
Other options in addition to the ones proposed by Morritz
Inside Tomcat: register a global object accessible by all servlets using the Global JNDI
Within the same JVM: start you shared resources (your static class, repository, etc...) and Tomcat programmatically (embedded) using a launcher like The Java Service Wrapper. You will need to define a small API implemented by your shared resource and usable by your servlets.
Distributed accross JVM: memcached, hazelcast, etc...

Categories