Accessing a servlet instance - java

while i can't really think of a practical use-case for such a scenario, but i purely intend this to be a curiosity driven question.
i understand the servlet container holds onto all the instances created of the servlets, and delegates request threads to these instances. it also makes sense to keep these instances managed, to avoid unwarranted calls to alter the lifecycle of servlet instances outside the purview of the container.
but is there really no way to access the servlet instances?

Prior to Servlet 2.1 (over a decade old already), you could use ServletContext#getServlet() for this. It's however deprecated since then. Simply because it's a bad design. If you want to invoke another servlet from inside a servlet in the request-response chain, just use RequestDispatcher#include(). If you want to invoke non-servlet specific methods of another servlet, then it's simply high time to refactor that code into a separate Java class which you could then import/use in the both servlets.

The container creates ONLY ONE instance of the Servlet and uses the same instance to serve multiple requests. There is "SingleThreadModel" which if you implement, container would create multiple instances of the Servlet but that is deprecated now.

Not through the standard Servlet API (so the answer is no).
You may, however, use your knowledge of the actual implementation and nasty tricks with reflection to get hold of the data structure used by the implementation to hold servlet instances, (so the answer is yes).
The servlet container may, however, have a SecurityManager in place prohibiting using said nasty tricks (so the answer is maybe).

Related

Tomcat keep webapp api running

I'm trying to create a web application for tomcat 7, but my problem is that I want to keep the whole backbone of the application running, so that my servlets can call the functions. Ex. I have my com.example.Main class which house all the instances to things like User managers and such. But instead of getting the main instance redefined on each servlet call, It would get defined once for all the servlets to use.
Best Regards,
- Roe
As far as I understand, you want a singleton. Check this answer for implementation.
But note that singletons are "evil". A more webapp approach is to not have it as singleton, but initialize it once in a ContextLoaderListener and then put it as a ServletContext attribute. Then each servlet can obtain it by getting it from the servlet context.
I agree with Bozho - you seem to be talking about a Singleton and I share his reservations about using them.
If you do implement it as a singleton, or use Bozho's suggested solution, it is important for you to understand that there will be only one instance of the class, potentially being used by many servlets at the same time. As a result, it is your responsibility to make sure that the class is thread safe, or your application will produce unreliable results.

Single servlet to handle a single page web application design

I have a single page web application designed to look like a desktop application using plain Jsp/Servlet. In the back end I have one servlet with action param being passed for various actions occurs on the single web page. 90% of the requests are ajax. When the functionality grows on the single web page there will be more actions exist under single servlet. Now my questions are
having single servlet to manage a lot of operations a good design? What would be the better design?
What is the performance benefit when having single vs multiple servlet?
Will the servlet code be unmanageable at one point when it grows?
For company policy reasons I can't use the spring mvc..
having single servlet to manage a lot of operations a good design? What would be the better design?
No. A single class having basically all the responsibilities of your backend is not good design. Unless it only serves as a dispatcher to actions, but then you would reinvent the wheel that all the existing MVC frameworks have already invented for years (Spring MVC, etc.). Frankly, I would fight against the "company policy", and use the appropriate tool for the job: Spring MVC, or JAX-RS, or any other modern framework that can be used to easily implement a proper REST backend.
What is the performance benefit when having single vs multiple servlet?
None.
Will the servlet code be unmanageable at one point when it grows?
Yes. You'd better follow the REST principles and assign different URLs to your different actions instead of using a parameter to pass the action. Moreover, all actions should not use the same HTTP method. Searching or reading information should use GET, while creating stuff should use POST and updating stuff should use PUT.
And of course, use one servlet per URL.
you can use jsf
its a single servlet
called FacesServlet
--
jokes aside,
you could use a single servlet, and create multiple classes to handle different scenarios and keep your servlet class under 100 lines of code with good design
but this is essentially writing mvc yourself
REST is the right approach as suggested by JB Nizet. Use JAX-RS for handling the request. In case you don't want to take that route, you can use a single servlet but use the servlet like a controller that send the request to different modules to handle it. Single servlet is fine as long as you don't put all the code in the same class.
In case you use multiple servlets, the design would get better when you plan to move one of the servlets to a different server. But with multiple servlets, the UI (html or java script) needs to handle routing to the right servlet
Code will be unmanageble only if you write everything in one servlet class... If designed correctly it should be manageable.

Servlet vs REST

I need to create 5 methods on the server side, which will work with binary data. The remote clients are applet and JavaScript. The Client will send files to the server, and the server must parse these files and then return the response as XML/JSON.
So I am confused - is it good practice to use REST-service in this case? Or should I use a servlet?
My colleague told me:
"Creating REST-service that will be used only by one Application isn't
good. REST must be created only when it will be used by many apps. And
REST has some disadvantages over servlet: REST is slower than servlet;
it more difficult to write thread-safe REST than servlet"
However, I see some disadvantages with using Servlet: I need to send a function name that I want to call (i.e. as extra HTTP parameter send function name)
and then inside the doPost method perform the following switch:
switch(functionName) {
case "function1":
function1();
break;
case "function2"
function2();
break;
//.... more `case` statements....
}
In case of REST I can simple use different URLs for different functions.
Also, in the case of REST, it more convenient to return JSON/XML from server.
You are confusing two paradigms here:
REST is a software architecture “style”;
Servlet is a server-side technology.
You can, for example, implement REST-like services using Servlets.
Well,
I wouldn't agree with your colleagues' opinion that isn't good to have rest used by only one application, since you may decide in the future to have different applications using the same rest api. If I were you I would choose the pure REST. Why?
If you're using some framework for rest implementation (let's say apache cxf or jersey) you get lots of stuff out of the box - you write POJO you get a rest, you get serialization and deserialization, to and from let's say, JSON object out of the box (eventually you will need to implement some JsonProviders but this is not a big deal).
It is intuitive to work (if you design your rest APIs well).
Very easily consumable by JavaScript clients (especially if you're using JQuery or something like that)
However, it strongly depends of what exactly do you want to do, if you have some strong transactional logic, the rest could be quite tricky. If you're only going to do POST requests (without using the other HTTP methods) you might want to use the Servlet since you won't have to work with additional frameworks and making more dependencies. Note that the REST is more or less an architectural concept and it does not contradict with the Servlet technology, if you're stubborn enough you can make a rest api only with servlets :-).
Hope I've helped.
First, you're speaking in terms of two different paradigms. It's kinda apples-and-oranges.
REST is a style of service that uses HTTP operations (GET, PUT, etc.) to read and write the state of resources. Think of resources as "nouns" and "things".
Servlet, on the other hand, is a software specification originally provided by Sun Microsystems for connecting HTTP requests to custom Java code. Servlets often speak in terms of method calls: "verbs" and "actions".
Since your question implies that you are looking to deal with input->output methods, just a plain servlet should do the job.
I cannot see any problems on using Jersey and create a REST service. I know that I'm a REST-taliban but it's really simple to implement this kind of architecture using JAX-RS, so... why not?
Your colleagues say: "REST must be created only when it will be used by many apps" but I cannot see how this can be true.Why I cannot create a REST service for a single app?
Sounds like your collegue is applying premature optimisation. If you can write it with a JAX-RS library quickly, do so... If it then proves to be the bottleneck only then do you take the time to rewrite as servlet.
In my experience the performance overhead of JAX-RS is not sufficiently big to justify the development and maintenance overhead of writing the equivalent in servlets directly where the problem maps well to JAX-RS
Depending on your container version, Jersey (or any other JAX-RS implementation) will still use a Servlet for dispatching requests to the appropriate handler.
If your application is truly RESTful, then JAX-RS will do what you want. Otherwise, consider using a FrontController to interpret the Request and forward it to the appropriate handler.
Also, don't confuse XML or JSON with REST. You will get these for free in most (if not all) JAX-RS implementations, but these implementations still delegate content marshalling to other libraries (e.g. JAXB).
Here is the similiar link. he has done it with simple servlet
http://software.danielwatrous.com/restful-java-servlet/

SOAP to Restlets strategy for multiple methods

I've been working with the Restlet library for the last couple weeks and from what I can see it is fairly impressive. The ability to be able to define a common interface for consumption by both the client and server surpasses any messy soap frameworks I've worked with.
However, something has been plaguing my mind that I just can get past:
Is there a good way to define Restlets with many methods?
My primary use case is that I have a soap web service that has 10-15 or so methods in it. As I see it, if I wish to translate this over to a Restlet I will need to separate this out into 8-15 interfaces depending on which methods become get methods vs post or put - I don't think you can have more than one verb method (get, post, put, etc) per interface. This seems like a cumbersome and clumsy solution.
I've thought of using some type of factory\map technique to mitigate this - but I wanted to make sure I'm not missing something better first.
Thanks
Even though coming from a SOAP background, it might be surprising, what you observe it actually a good thing because your web API is becoming more and more RESTful.
In REST/HTTP, methods are standard and limited (by design) and to compensate we create as many resources/URis as necessary.
Regarding JAX-RS, it doesn't have the same client/server uniformity. I would recommend staying with the core Restlet API in general as it is more powerful/extensible.
If you could list your method names, that would help suggest a proper mapping to HTTP resource and methods, I'm not sure you need that many interfaces in the end. Even if this is the case, there server-side implementation will be easy and more maintainable which also has benefits.
Hope this helps
There's a JAX-RS extension for Restlet. JAX-RS provides the #Path annotation that is used identify the URI of the resource. Paths can be attached either to the type or to a method. Routing should be then done by the container instead of explicitly defining router rules.

Singleton in Java App Server.. How bad of an idea is this?

I am currently working on some older java code that was developed without App Servers in mind. It is basically a bunch of "black box code" with an input interface, and an output interface. Everything in the "black box" classes are static Data Structures that contain state, which are put through algorithms at timed intervals (every 10 seconds). The black box is started from a main method.
To keep this easy for myself, I am thinking of making the "black box" a Singleton. Basically, anyone who wants to access the logic inside of the black box will get the same instance. This will allow me to use Message Driven beans as input to the black box, and a JMS Publisher of some sort as the output of the black box.
How bad of an idea is this? Any tips?
One of the main concerns I have though, is there may be Threads in the "black box" code that I am unaware of.
Is there such thing as "application scoped objects" in EJB?
Note: I am using Glassfish
If you use a simple singelton, you will be facing problems once you enter a clustered environment.
In such scenario, you have multiple classloaders on multiple JVMs, and your sinlgeton pattern will break as you will have several instances of that class.
The only acceptable use for a singleton in an app server (potentially in a clustered environment) is when you the singleton is totally state-less, and is only used as a convenience to access global data/functions.
I suggest checking your application server vendor's solution for this issue. Most, if not all vendors, supply some solution for requirements of your sort.
Specifically for Glassfish, which you say you are using, check out Singleton EJB support for Glassfish. It might be as simple as adding a single annotation.
I would say that creating a singleton is actually the only viable idea. Assuming that code inside this "black box" is known to use static fields, it is absolutely unsafe to create two instances of this facade. Results are unpredictable otherwise.
Far from being a bad idea, it actually sounds to me like potentially quite a good idea.
Just from a program design point of view: if your black box is conceptually an "object" with properties and methods that work on them, then make it into an object, even if there'll only ever be one of them instantiated.
It should work, but there are some issues you may have to deal with.
Threading, as you have mentioned. An MDB is run in the EJB container where you cannot create your own threads, so you have a potential problem there. If you have access to the actual code (which it sounds like you do), you may want to do some refactoring to either eliminate the threads or use an "approved" threading method. The CommonJ TimerManager will probably work in your stated case since it is performing some task on an interval. There are implementations available for most app servers (WAS and Weblogic have it included).
Classloading - This is dependent on you configuration. If the singleton is created and manipulated from MDB's within the same EAR, you will be fine. Separate EAR's will mean different classloaders and multiple instance of you Singleton. Can't comment on whether this would be a problem in your case or not without more information.
I'm missing a point? You mentioned that the 'black box code' contains state. MDBs may be limited to 1 instance per destination but without proper configuration you will end up with a few MDBs. All of them working with your single instance of 'black box code'. For me it seems this is not a good idea, because one bean will override the 'black box code' state a other bean has created a few ticks before.
It seems to me that the artifact that better fits to your requirement is a JBoss MBean. (If you are thinking on JBoss as AS candidate).
Standard MBean Example
MBeans can also be deployed as Singletons, in case of JBoss clustering.
Clustering with JBoss
I hope that this is useful for you.
Rafa.
Fix the code to get rid of the statics as soon as possible. Singletons are not a step in the right direction - they just add extra misdirection.
Don't use Singletons where state may change.
Exposing the global instance of your black-box class doesn't seem like the way to go. Often times, singletons will seem like they will make things easier on you, and in a way they can, but it often comes back to bite you and you end up having to restructure a large chunk of your code.
In the webserver world, an object can be scoped to the request, the session, or the application. Perhaps what you need is a application-scope object.
Search the docs for "application scope object" or "application lifetime object".
Why not create a rest interface for the blank box thingy and let clients make http calls ?
IMO, it's a good idea to have an EJB container of your Singleton needs. In Java EE 6 placing a #Singleton annotation in your session bean gives you a named singleton.

Categories