Web Scripting for Java - java

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!

Related

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/

Create a html response when user visits internal URL

When a user hits a particular internal URL I need to return some html that is created dynamically.
Some back end services will be called to genrated a list of keys which is then used to generated a list of html
href links which are displayed to the user.
For this I am considering using a servlet. Is this a good methodology ?
Since servlets have been around for some time maybe there are newer/better ways of implementing this ?
There are tons of solutions, most of them (in Java) being based on the servlet API. If you use Spring already, Spring has a module called Spring MVC, which is a framework based on the servlet API to create web applications, based on the MVC pattern:
Model holding the data from the database
View (implemented, most of the time, using JSPs) generating markup based on the data contained in the model
Controller getting the data from the database, and dispatching to the appropriate view
This is a good pattern used by most web frameworks, but every one has its own way of doing, strengths and weaknesses.
You could do with a simple servlet, but generating markup from a servlet is ugly. That's why servlets are usually used in combinations with JSPs, following the MVC pattern. You could implement a micro-MVC framework by yourself, using only servlets and JSPs, but Spring-MVC and other frameworks offer so many additional advanteges that the investment is worth it. I personally like Stripes very much, and it's very simple.
Servlets are the Java way of exposing simple interfaces for HTTP request.
This can also be achieved by a REST framework like Jersey, but its a bit more complicated, so if you need a simple one opertaion interface, I'd go with servlets.

Why use a framework for RESTful services in Java instead of vanilla servlets

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.

Architectural Differences in Java MVC Web Frameworks

I'm trying to choose an AJAX-friendly Java framework for my first web application and am interested in first
understanding the architectural differences between the different flavors that are out there.
I like the concept of MVC frameworks, and so am primarily considering the following:
Any JSF variety (ICEFaces, RichFaces, PrimeFaces, etc.)
Spring Web Flow
ZK
Wicket
I've downloaded each of these projects and tried to follow their samples/tutorials, and there is
so much information to ingest I figured I'd take a breather and come here to cover some preliminaries
first.
I'm interested in how each of these frameworks implements the MVC pattern. Obviously, something rooted
in JSF (like ICEFaces) is going to have a different architecture than Spring. I'm sure that this is a
huge question, so I'm not looking for a full-blown tutorial on each of these frameworks; I'm just
curious as to what sort of artifacts (Java sources, XML config files, etc.) a developer has to write in
order to build a single AJAX-driven page using these. I'm interested in the differences to their approach,
nothing more.
For instance, I would imagine that each framework at some point uses a FrontController (or its likes) to
map HttpRequests to the right Controller implementation. That Controller (bean) would then need to do
some processing, possibly hit the database for some information (using ormapping and forming the Model), and
then construct a View/HttpResponse to send back to the client. This is an oversimplification I'm sure, but
there has to be an easy way to explain the high-level architecture for how each of these frameworks accomplishes
that.
Struts uses the ActionServlet (with Struts2 now its just Action) as the controller and model and jsp is the view.
For Spring MVC is achieved by DispatcherServlet which does the routing and Model is not bound to any framework related object you can use any.
JSF - UI jsp or jsf itself, Model - ManagedBean, Controller - FacesServlet.
I did some similar search for my own project a while ago, have a look at the links below:
Comparison based on multiple parameters : http://static.raibledesigns.com/repository/presentations/ComparingJavaWebFrameworks.pdf
Difference between JSF and Struts
http://struts.apache.org/2.0.14/docs/what-are-the-fundamental-differences-between-struts-and-jsf.html
Somewhat related post
https://stackoverflow.com/questions/7633583/which-mvc-is-better-spring-or-struts
Spring and JSF
http://blog.springsource.org/2007/04/21/what-spring-web-flow-offers-jsf-developers/
Spring MVC : http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html
Best Fit For JSF Component Library: Primefaces based on my own experience
From IBM Clearing the FUD : http://www.ibm.com/developerworks/library/j-jsf1/
Hope this gives you some insight.
Have a look at Matt Raible's talk on Comparing JVM Web Frameworks here. You can also consider looking at Spring MVC and 'Tapestry`.
Also, this link gives you a matrix on capabilities of various java web frameworks.
You should also check out the Play framework. I have used it a little and really like it.
It is very easy to get started with minimal configuration (reminds me of Rails).
http://www.playframework.org/

Java Framework for integrating WSDL, REST, etc

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.

Categories