Post data from Server side in Spring MVC - java

I am making a automation website to send multiple files to an another site to prevent filling form every time to send a file.
I want to to make the POST request from server, because AJAX doesn't allow request to other domains.
How I can make this?
I am using Spring MVC3

Use apache http components - it allows you to perform http requests. You can also use (without 3rd party libraries) new URL(..).openConnection(), but it's less pleasant to code with it.

You can use Apache HTTP Components to implement pretty much any HTTP calls you want in your application. Also, note that it is possible to do cross domain AJAX with certain helper technologies like Flash ... if you really needed too.

Related

Create rest api on java - reverse endpoints

I am creating a rest api on java and I got a problem that users will have to poll my REST URL often to get changes in data. But then I think what if I will send them a special REST call to their server to notify for changes? It will be not a good api because they will have to have their procession points, etc. How to resolve this situation?
Perhaps you are not using the right tool for the job. REST over HTTP may not suit your needs.
Have you considered Server-Sent Events (SSE) or even WebSockets? They may fit your needs better.

Send notifications from Java servlet to HTML pages

I have a Java servlet from which I need to send few notifications to the HTML page before I send the final response (which is a PDF file).
Basically I need to keep the user updating on steps I am performing while generating the PDF for them.
I guess, one way could be set various attributes using HttpSession and have them printed using JS. But I don't know how to do that dynamically without loading the page again.
Any idea on how can this be done? I am kind of new to JSP and servlets.
There are two ways:
AJAX polling - you send ajax requests periodically, and the server responds. The page does not get refreshed. Check jQuery for an easy way to make ajax calls
Comet - that's an umbrella term for what you are trying to do. Usually it means keeping an open channel with the server. There are many ways to implement comet (including the option above), but in Java, on the server side, there are two things to check:
Servlet 3.0 asynchronous support
Atmoshphere - chooses the best underlying mechanism provided by the container, which includes the async support above
You should probably look forward to use some implementation of COMET (with js library of choice).
If your html code is allowed to use html5 features, you could also use websockets

Best way for handle Read HTTPRequst post data on Restful api

What is the best way of save data using Restful web service without using Ajax? As a example I need to add a new Customer to the database using submit button.
What is the best way of transfer data format (text,json,xml) ?
How to read POST or GET data from HttpRequest object?
If you can please give me a example in java .
Thank you
I think you need to separate the concepts a bit. A "Restful Web Service" is a web service designed using REST principals, whereas AJAX is a set of technologies used often on the client side for asynchronous requests to multiple resources (without fully reloading the page). The web service really shouldn't care how the HTTP request is generated, just the contents of the HTTP request.
Now if you're concerned about writing a rest service in Java, I would highly recommend looking into JAX-RS and the reference implementation Jersey. There are lots of examples of how to get up and running. You can use MessageBodyReader implementations are to convert data from the HTTP request entity into Java objects.
Obviously this is not the only way to get started with writing a Restful web service in Java, but is one way.
It's very definitely worth your time to carefully study Richardson and Ruby's RESTful Web Services to learn the REST architectural style. In addition to #ach_l's recommendation to use Jersey, take a look at the Restlet Java framework, which is completely wonderful.

Implementing an HTTP proxy to overcome cross-site AJAX requests restrictions (?)

I have a Spring-MVC webapp (3.0.5-RELEASE) which needs to access JSON webservices from another webapp on a different sub-domain (from the client/browser via AJAX).
I've solved this in the past by either:
writing a simple controller that proxies the requests, using Apache Commons HttpClient to handle the requests. Thus overcoming the cross-site/cross-origin request security limitations of most browsers
implementing a JSONP service on the server side (when calling our own JSON services) - not always possible
In the case where JSONP is not possible, is there a better way of doing (1.)?
and/or
Is there a library that will handle this for me? So I don't have to write all the HttpClient code myself - its not a lot of code, but I wonder if I'm (badly) re-inventing the wheel.
I have often had to consume third party web services (API), and as you mentioned, JSONP is not always an option. This is how I go about designing:
If the API is user centric, it has to provide a jsonp interface and that's what I will use. User centric means that you cannot perceive any reason to call the API, do some computations with the response, may be call one of your ajax services and then combine the response and show the user.
If my use case includes calling the API, and then acting on the response, like calling additional services from my application, combining the data and then showing it to the user, I would prefer not doing this in the browser. I would instead use RestTemplate and make backend api calls to the service. In which case there are no cross domain restrictions.
The only case where using a Server Proxy to bypass jsonp is when you are creating a Product that allows people to build custom plugins, plugins which are hosted on your page, but need to make Ajax calls to the app developers servers. This is a very involved case! (As as example look at how Apigee creates Public Facing REST API around your existing urls, or how Zendesk allows you to develop apps)
Hope this helps.

AJAX Using a REST API Without Server Side Framework

I am building a REST based API (Read only) for accessing services of my application. I plan on writing a web application that will leverage these APIs to provide basic information on the status of the application. I plan to use AJAX (using jQuery) to show the information.
Originally I planned on using Grails, Spring MVC, RoR or one of the web frameworks to handle the back end of my application. The REST APIs I will be providing though are already built on a stanalone REST framework so I would only be leveraging the web framework for the core application and not the business logic. In the future, I might need the server side framework to handle other tasks but for now most of the work is done in the REST APIs.
My question is, should I bother with using a web application framework on the server side? I should be able to make all the API calls I need from AJAX directly from the browser. I cannot think of much I would need to do on the server side. Would it make sense to have the application be standard HTML + AJAX + REST?
Its hard to say without actually knowing more about your current setup. This is what your situation sounds like:
You already have an app ready to go with all of the business logic contained. Sounds like its written in Java?
You already have the services written and exposed through a REST api using some other standalone framework. Meaning that if you wanted to, you could access the data right now with the browser without any extra work.
You have not yet built the web application, but when you do, it will get all of its content from the REST api using XHR and jquery. I say that, because otherwise, I would think that you would already be using some kind of framework to generate the other content.
If I am correct in my assumptions, then I would say that you have no need for an additional framework layer. Grails, RoR, SpringMVC my use ajax, and aid in exposing REST services, but the bulk of what they provide is an easy way to make an application that must generate html on the server, deal with form submissions, and handle sessions in a request/response cycle. It doesn't really sound like you'll be doing any of that, and it will likely make your app more complicated.
If you did at some point need the things that rails etc. provides, I would say that you may not need to use rails to expose the rest apis you have now. You could use rails just for what you need, and continue to use what you have for the REST api.
Well, the AJAX calls need to pull data from a server somewhere. If the goal is to avoid a complicated setup on the server side, CherryPy can keep the server side code VERY small.
I've written a simple exapmle below. The first class would be where you put the logic for your ReST API. The code below the class is all you need to get the server up and running.
Install Python 2.6, save the code below to restExample.py. Then in your command line run the python file by doing "python restExample.py". Point your browser to http://localhost:8080/blog/999 and see some JSON come back.
import cherrypy
import json
# Create the controller
class Blog_Controller(object):
def get(self, entryID):
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'title':'Entry Title from DB', 'entry_text': 'Text From DB'})
def update(self, entryID, titleFromPOSTFormInput, textFromPOSTFormInput):
# Update DB with passed in arguments. entryID comes from URL,
# other two entries come from POST
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'success':True})
# Setup URL routes
d = cherrypy.dispatch.RoutesDispatcher()
d.connect(name='blog_entry', route='blog/:entryID', action='get',
controller=Blog_Controller(),
conditions={'method': ['GET']})
d.connect(name='blog_entry', route='blog/update/:entryID', action='update',
controller=Blog_Controller(),
conditions={'method': ['POST']})
config = { '/' : { 'request.dispatch': d } }
cherrypy.tree.mount(root=None, config=config)
# Start the webserver
engine = cherrypy.engine
try:
engine.start()
except:
sys.exit(1)
else:
engine.block()
It sounds like this might be a good use case for GWT with Restlet.
Forgive me for tooting my own horn, but if you are doing AJAX REST stuff with jQuery, you should probably check out my JSON-REST plugin:
http://plugins.jquery.com/project/rest
If you are getting XML back, then this won't be as useful, but you may still be able to adapt some of the code to your needs.

Categories