I have two web applications say App1 and App2. I want to call a servlet which is in App2 from a servlet in App1. I'm using URLConnection for this. I'm able to pass parameters to the servlet in App2 also and I'm also able to receive response from the servlet as string. But I want to send java objects from the servlet in App2 and receive them in servlet of App1. How to achieve this?
Depends.
If those webapplications runs at physically the same webserver in the same servletcontainer, then just set it as a request attribute and forward the request to the other context:
request.setAttribute("name", object);
ServletContext app2 = getServletContext().getContext("app2");
app2.getRequestDispacher("servletUrl").forward(request, response);
The other context will be able to obtain the object as follows:
Object object = request.getAttribute("name");
This only requires a server setting that the contexts are accessible by each other. How to do this depends on the servletcontainer. In Tomcat for example, you just need to set crossContext attribute of the webapp's <Context> element to true.
<Context crossContext="true">
Then it will be available to other contexts. For other servers, consult its documentation.
If those webapplications runs at physically different webserver, then there are several options:
Convert to String and send as parameter. On retrieval, convert back from String. JSON is a nice format for this. Google Gson offers possibilities to convert between fullworthy Java objects and JSON and vice versa. If you're using GET and the request URI gets pretty long, over 2KB, then consider using POST instead of GET, else the URI may be truncated by the server. Pros: better reuseable service. Cons: hard to send binary data.
See also: Converting JSON to Java.
Send a multipart/form-data HTTP POST request using URLConnection or Apache HttpComponents Client as per RFC2388 and process it on the other side using Apache Commons FileUpload. Pros: standard specification, possible to send binary data. Cons: more code.
See also: How to use URLConnection.
Serialize the Java object, write it raw to the URLConnection#getOutputStream() using ObjectOutputStream and retrieve it raw from the HttpServletRequest#getInputStream() and unserialize it using ObjectInputStream. Pros: easy. Cons: not reuseable, tight coupled.
See also: Object Streams and Lesson: Serialization.
Use Serialization
Instead of sending HTML you'll send objects streams.
Just, be aware, to add extra security, you don't want to some external source inject poisoned objects into your calls.
Related
I'm a Jersey / REST newbie and am trying to write a simple web service. The issue I have is the storage of data between requests.
Servlets can access sessions but I didn't believe Jersey / REST allows this.
I am currently writing this service so that an Android app will make RESTful requests to Tomcat.
Now I am not sure yet of the type of request these will be: should they be URLs with parameters, or simply an XML string? The type of data to be transmitted from the app will include addresses of RSS feeds and keywords and sundry metadata.
The XML responses from the server will again consist of RSS feed addresses, keywords, frequencies of the keywords and other metadata.
The idea at the moment is to use JAXB on both app and server to make up and break down the XML into Java objects.
JSON or GSON are not available alternatives here.
But what about storing data between requests? Is it enough to store all the relevant variables in XML if XML forms the request and response actions, where each request will have an ID number referring to the server's database.
Or is it better to use the session context for servlets via REST?
Apologies if the above sounds vague. I am a Jersey / REST newbie.
While as has been said it is generally recommended your WS calls to be stateless, Jersey does rely on Servlet, so you can inject the HttpServletRequest and get the session from there:
#GET
public String getMethod(#Context HttpServletRequest req) {
HttpSession session= req.getSession(true);
...
You can then configure your web server session storage to memory, cookie, cache, db, or whatever.
REST webservices are based on the HTTP protocol which is a stateless protocol.
In my opinion, saving state in your webservice is not a good idea.
You should use cookies to store user data.
JAX-RS services can either be singletons or per-request objects. A singleton
means that one and only one Java object services HTTP requests. Per-request means
that a Java object is created to process each incoming request and is thrown away at
the end of that request. Per-request also implies statelessness, as no service state is held
between requests.
this is my first post on stackoverflow.
I am quite good at Java SE and client side Java Programming, but new to Java web development.
When I search for Java webframeworks, a huge amount of framework are offered, but nothing really seems to fit my needs.
What I actually want is a dumb server and a smart client.
I want the client to ask for certain information and the server to return the requested information in a xml or json format, so that the client itself manages the data.
In most cases the webframeworks render the html pages etc. on the server side, but I just want for example to use AJAX or the android xml parser to get the information and then fill the UI on the clientside.
I am not sure, if Webservices are the right thing for me, because I want to make several async requests to the server.
Or should I simply use servlets, which just return the right xml on request.
A second thing is how to handle the authorization and authentication of the users, which send the request to the webserver.
I do not want to allow everyone to receive the xml or json, which is generated by the server.
In short:
Is there a java based webframework, which can handle authorization and authentication of users and just returns xml or json to a smart client?
Which java based webframework fits best to my needs?
On the following webpage my aim is described, but unfortunately there is no hint how to implement such a "dumb" server...
http://seng130.wordpress.com/lectures-2/web-application-architecture/
You will likely need to use multiple frameworks. Spring-Security to handle your url intercept based on authority. Then use Servlet with Spring-MVC to handle the request within the Controller methods. Tutorial here: http://static.springsource.org/spring-security/site/tutorial.html You can have those methods return string values of JSON or XML. I would suggest using Jackson to convert your objects to a JSON form on the fly and the javax libraries for XML.
Example of Spring-MVC with Jackson:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
Example with Jersey servlet and Jackson
http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
I understand web service provides all SOAP,WSDL support, and it stands at a higher level than Servlet.But if I just simply wanted to expose a rest api to allow another application(client) to make a few very easy queries which can be done even via web browser.
eg. http://serverIP/getUserInfo/123
where 123 is like user's id. Let's just assume user info is returned as json.
Questions are:
Is there a big difference between implementing it in Servlet and Jersey?
If the client application is written in .net, does that make any difference?
Is it true that jax-ws allows you to specify the MIME type to be json while servlet's client has to parse the result?
From performance perspective, which one is quicker? I noticed that normally, Jersey is meant not to be deployed on Tomcat while Servlet is.
Is there a big difference between implementing it in Servlet and
Jersey?
Jersey is a framework that makes it a lot easier to write Restfull services. It uses the Servlet API, so it abstracts away a lot of the low level stuff.
You have to write a lot more code doing it using only the Servlet API, and the code has to deal with a lot of low level stuff that you can configure in a declarative way using Jersey.
If the client application is written in .net, does that make any
difference?
No
Is it true that jax-ws allows you to specify the MIME type to be json
while servlet's client has to parse the result?
Jersey lets you declare the mime type using annotations, but that's only for convenience, you still have to parse the incoming payload to check for correct mime type.
From performance perspective, which one is quicker?
Depends if you are able to write a faster implementation than the Jersey team. Jersey use servlets as well.
I noticed that normally, Jersey is meant not to be deployed on Tomcat
while Servlet is.
Tomcat is a servlet container. Jersey uses the servlet API to communicate over HTTP. There are web-frameworks that don't use servlets, for instance Play framework.
I'm creating a Java application that uses Hunch's API, but the problem is I have no clue as to how I can use a web API in Java. Any ideas?
That depends on what the API provides, generally you'd need a web server (like Tomcat) to run a web framework.
If it's just an api to communicate with a service via HTTP (maybe webservices) then have a look at the corresponding libraries (JAX-WS etc.).
Edit: I looked up Hunch API, and assume it is this: http://hunch.com/developers/v1/
It seems like it would return JSON encoded data, so you might use the URL class to read data from an URL. That data would be a JSON string which then needs to be decoded using one of the many JSON libraries out there (e.g. JSON-simple).
Im a little confused on the varying definitions and implementations of web services available as implementations. Need some clarification please.
Ones I have used till now:
If a vendor gives me a specific format of XML that I can send populated with data to request and I make a simple HTTP POST over the internet passing in the XML String as the payload, is this a web service call ? If so, is there a specific name to it, this kind of web service ? Because obviously, it does not use anything like Axis, WSDL or SOAP to establish this connection.
A variant of this is If the vendor gives me an XSD, I use JAXB to make a java class out of it and pass in the serialized version of the object, which eventually works out to be the same as option 1.
RESTful web service: Vendor gives me a URL like http://restfulservice/products and I can make HTTP Requests to the URL and depending on what HTTP verb I use, the appropropriate action is called and the response sent over the wire.
Ones I have only read about\ have a vague idea about
SOAP. How does this work?.. Ive read the W3Schools tutorial and I undertsand that there is a very specific form of XML that is standardized according to W3C standards that we use to pass the same kind of messages as we did in option 1. But how does this work in real life? Vendor sends me what? Do I generate classes? Do I serialize some objects and http post them over to an address? Or do the generated objects themselves have connection methods that will do them for me?
What about WSDL? When does a vendor send me WSDL and what do I do with it ? I guess I can generate classes from it. If yes, then what do I do with the generated classes ?
When do I need that axis jar to generate classes from something that the vendor sends ?
As you can see, I have some clear and other mostly vague ideas about the different kinds of web services available. would help if someone ould clarify and\or point to more real-world resources. I've looked a little bit into Java Web Services on the internet and the numerous four letter acronyms that get thrown at me make me dizzy.
Thanks
If a vendor gives me a specific format
of XML that I can send populated with
data to request and I make a simple
HTTP POST over the internet passing in
the XML String as the payload, is this
a web service call ? If so, is there a
specific name to it, this kind of web
service ?
This is still a web service, yes. It doesn't have an "official" name, I usually refer to it as XML-over-HTTP, mainly because I can't think of a better name.
SOAP. How does this work?.. Ive read
the W3Schools tutorial and I
undertsand that there is a very
specific form of XML that is
standardized according to W3C
standards that we use to pass the same
kind of messages as we did in option 1
SOAP provides a standard wrapper layer around the sort of messages you were sending in (1). This wrapper provides information such as an indication as to which operation you are invoking. It can also provide security services, transaction information, and so on. It's a pretty thin layer, usually.
What about WSDL? When does a vendor
send me WSDL and what do I do with it
? I guess I can generate classes from
it. If yes, then what do I do with the
generated classes ?
Again, WSDL is a pretty thin layer, this time around an XML Schema. It defines the operations that SOAP messages will invoke at runtime, as well as the Schema types of the requests and responses. Its a way of formalising the XML document exchange interface.
Say, for example, you had an XML Schema, and have a web service as you described
Using JAXB to generate java source from the schema
Send XML documents conforming to that schema over HTTP to the web service
With WSDL and SOAP, you would extend this a bit :
Write a thin WSDL wrapper around the XML Schema, formalising which operations are available.
Use a WSDL import tool to generate client/server stubs for that WSDL/Schema. In Java, this often incorporates JAXB.
Use a SOAP client/server to invoke the web service
As you can see, it's essentially the same process. The difference is that SOAP/WSDL provides additional information and context to the tools, allowing those tools to do more of the work for you. It's not hugely different, though.
If you get a WSDL document from somewhere, all you really need to know is that it defines a service interface. You run it through your favourite language's binding generator to make some code that you can use to call the service. Typically that means you'll be talking over the wire to the service using SOAP messages over HTTP. SOAP's just a wrapper round sending pretty arbitrary XML messages.
Axis is a library for doing this stuff in Java (both client and server side). I suspect that there are better implementations in other libraries.