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/
Related
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.
I know there are a few questions regarding the libraries you can use to do RESTful services in Java, but what is the value in using them against vanilla implementations. I mean, if i was looking to create the url structure described by Wim
www.example.com/images
www.example.com/images/id/num
www.example.com/images/tag/num
www.example.com/images/tag/num/num/num
Would it not be easier (for future developers) and faster (to implement and learn) to map the url pattern /images to a servlet and have a line or two that parses the url for the parameters instead of learning, implementing and configuring one of these libraries to do it for you.
Apache CXF
Jersey (popular)
Restlet (pioneer of JAX-RS)
RESTEasy
Essentially what I am asking is... What is the value in using a RESTful Java framework? Would it not be adding a lot of complexity, in the implementation, for a simple problem?
EDIT: This jersey code is handled very neatly and everyone should know how to do it in servlet form if they are looking into libraries to do it for them.
#Path("/helloworld")
public class HelloWorldResource {
// The Java method will process HTTP GET requests
#GET
// The Java method will produce content identified by the MIME Media
// type "text/plain"
#Produces("text/plain")
public String helloWorld() {
// Return some cliched textual content
return "Hello World";
}
}
If all you are going to be doing is a "service" that returns text that is driven by URL parameters, so plain text returns, is a framework necessary?
Would it not be easier (for future developers) and faster (to implement and learn) to map the url pattern /images to a servlet and have a line or two that parses the url for the parameters instead of learning, implementing and configuring one of these libraries to do it for you.
…
Easier? It's certainly not easier to write — you've got to do all the path extraction yourself and all the method handling and all the content type negotiation (in both directions) and all the cookie handling and the object deserialization/serialization thunks and … well, lots of low-level stuff that would all need testing and debugging — or easier to maintain either, since the JAX-RS interface lets you operate at the level of resources (the natural characterization of RESTful webapps) instead of requests; with much experience, maintenance is easiest when the gap between conceptual model and implementation is smallest. It's also not faster to implement (because the low-level implementations of JAX-RS have already been tested and debugged for you; less for you to do) and the cost of learning it isn't very high as it is a mostly declarative API with very few surprises.
OK, these benefits might not seem so much when you're only dealing with simple webapps. After all, you can hack something out in very little time and put the resulting lash-up online. You'll then have to pray that you got it right without significant unexpected avenues for exploits or denial-of-service attacks. And the maintenance programmers will have to understand just what those regular expressions you've sprayed through the code do (Good Luck With That!) when adding small features or fixing bugs. But as the webapp gets larger, the benefit of having a tested library to handle all the low-level stuff really does win out.
(Before you ask, some of the libraries you mention will merrily install themselves as servlets; this allows your code to just describe the business logic of the servlet and declare how mapping to the wire is done in abstract terms. That's just enormously easier.)
JAX-RS is a very well designed API that makes mapping HTTP requests to methods, extracting parameters from various parts of a HTTP request, handling content negotiating, and many other low level tasks very easy.
Using JAX-RS, mainly via Apache CXF, for roughly two years now, I'd always prefer it over plain Servlets.
Frameworks are used to make you task more easier. i agree that we can do the same thing by implementing servlets and then parse the url and then implement the basic logic.
Bu if you are using framework like jersey then u don't have to worry about those parsing patterns and other similar tasks. ServletContainer class will take care of this (parsing url in it's service method) and there are lots of other classes also which will make your task easier.
And one more thing we are taking only a one scenario (matching patterns) but when our requirements will grow the same code written by our own servlets will become more complicated and complex.
I would go with using Jersey or a library in this case, if it does the following (adds enough value):
the config for the URL is all self-contained within one file, with the source
there are no hidden config files or overly verbose configs (e.g. web.xml)
the parameters are nicely mapped to strongly typed variables (e.g. use of annotations)
it is not convoluted to get to the values of parameters (e.g. RESTlet)
the overhead for running the library is low (I have had bad experiences with reflection solutions in other libraries)
it is well documented
it is well adopted
In such a scenario, I find that using a library would add value to my project for the effort required to use it. Jersey does seem to mach the requirements quite adequately, although I have not given other frameworks enough investigation yet.
At work, we currently have a WSDL interface as well as a semi-RESTful interface that we're looking to expand upon and take it to the next level.
The main application runs using Servlets + JSPs as well as Spring.
The idea is that the REST and WSDL are interfaces for an API that will be designed. These (and potentially other things in future) are simply a method through which clients will be able to integrate with the interface.
I'm wondering if there are any suggestions or recommendations on frameworks / methodologies, etc for implementing that under-lying API or does it make sense simply to create some Spring beans which is called either by WSDL or REST?
Hope that makes sense.
Have a look at Eunicate it is great . You are using spring , Spring has had support of SOAP for a while and Spring 3 has support of REST (Creating and Consuming).
Your approach makes sense. Probably the most important advice is to make the external API layer as thin as possible. You can use Axis, Apache CXF, Jersey, etc. to handle the implementation of the REST or SOAP protocols, but the implementation of those services should just load the passed in data into a common request object, and pass that into a separate service that handles the request and returns a response object which the external API layer will marshall into the correct format for you.
This approach works especially well when you have a competitor providing similar services and you want to make it easy for their customers to switch. You just build a new external API that mirrors the competitors, and simply translates their format to your internal api model and provided your services are functionally equivalent, you're done.
This is a really late response, but I have a different view on this topic. The traditional way as we know it is to unmarshall xml to java and marshall java to xml. However if the wsdl changes then it would effectively be a structural change in the code which would again require a deployment.
Instead of the above approach if we list the fields mentioned in the wsdl in a presistent store, load the mappings in memory and prepare our structures based on these mappings we would have to have many less changes for this..Thus IMO instead of using existing libraries a configurable approach to unmarshalling and marshalling should be taken.
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.
What is a good way to render data produced by a Java process in the browser?
I've made extensive use of JSP and the various associated frameworks (JSTL, Struts, Tapestry, etc), as well as more comprehensive frameworks not related to JSP (GWT, OpenLaszlo). None of the solutions have ever been entirely satisfactory - in most cases the framework is too constrained or too complex for my needs, while others would require extensive refactoring of existing code. Additionally, most frameworks seem to have performance problems.
Currently I'm leaning towards the solution of exposing my java data via a simple servlet that returns JSON, and then rendering the data using PHP or Ruby. This has the added benefit of instantly exposing my service as a web service as well, but I'm wondering if I'm reinventing the wheel here.
I personally use Tapestry 5 for creating webpages with Java, but I agree that it can sometimes be a bit overkill. I would look into using JAX-RS (java.net project, jsr311) it is pretty simple to use, it supports marshalling and unmarshalling objects to/from XML out of the box. It is possible to extend it to support JSON via Jettison.
There are two implementations that I have tried:
Jersey - the reference implementation for JAX-RS.
Resteasy - the implementation I prefer, good support for marshalling and unmarshalling a wide-range of formats. Also pretty stable and has more features that Jersey.
Take a look at the following code to get a feeling for what JAX-RS can do for you:
#Path("/")
class TestClass {
#GET
#Path("text")
#Produces("text/plain")
String getText() {
return "String value";
}
}
This tiny class will expose itself at the root of the server (#Path on the class), then expose the getText() method at the URI /text and allow access to it via HTTP GET. The #Produces annotation tells the JAX-RS framework to attempt to turn the result of the method into plain text.
The easiest way to learn about what is possible with JAX-RS is to read the specification.
We're using Stripes. It gives you more structure than straight servlets, but it lets you control your urls through a #UrlBinding annotation. We use it to stream xml and json back to the browser for ajax stuff.
You could easily consume it with another technology if you wanted to go that route, but you may actually enjoy developing with stripes.
Check out Restlet for a good framework for exposing your domain model as REST services (including JSON and trivial XML output).
For rendering your info, maybe you can use GWT on the client side and consume your data services? If GWT doesn't float your boat, then maybe JQuery would?
Perhaps you could generate the data as XML and render it using XSLT?
I'm not sure PHP or Ruby are the answer if Java isn't fast enough for you!