Spring - from JSON response to webPage - java

I have built a simple service in Spring:
#RequestMapping(value = "/list", method = RequestMethod.GET)
public #ResponseBody List<Person> eventList() throws ParseException {
return personDAOImpl.list();
}
When I invoke the corresponding URL, I see a JsonObject list like this:
[{"id":2,"name":"John"},{"id":3,"name":"Jack"},{"id":4,"name":"Sam"}]
This service will be invoked both from a mobile app (and I know how to use a Json response in this case) and from a browser, and so I want that the /list service returns a Json.
By now, if I write the url in a browser (typing localhost:8080/myproject/eventList) I simply obtain the aforementioned Json String displayed on the screen.
How could I obtain a user-friendly interface that shows to the user a more friendly, like if I used a jsp?
ps: I have already used a service that successfully returns a jsp page (using ModelAndView), and that shows a table with the items, but I repeat that I would like to get a json response and than parsing it in a different way depending from the client (web browser or mobile app).
Thank you in advance!

You could build a client app which makes requests to your API using JavaScript.
For example,
localhost:8080/jsp/home returns a jsp page Home.
The Home page makes AJAX request (using JavaScript) to localhost:8080/myproject/eventList and recieves the JSON object. jQuery.get()
The Home page adds (using JavaScript) some visual elements to html. jQuery.append()
That's all.

Related

How to get "POST" method to show with Rest Web Services

I am new to Rest web services, and I am trying to figure out what I am doing wrong. When I run on server with the address:
localhost:8080/rest/webresources/error
Then the output message I want (the error message) shows up.
But when I run on the server to show input values using:
localhost:8080/rest/webresources/inputvalues
it doesn't. What am I doing wrong? I feel like my path is wrong, and I tried different combinations of it, but it still gives me a 404 not found error.
#Path("error")
public class RestWeb {
#GET
#Produces(MediaType.TEXT_HTML)
public String getText() {
return "<body> Error. Invalid data. </body>";
}
#POST
#Produces(MediaType.TEXT_HTML)
#Path("/inputvalues")
public String getParamText(#FormParam("travel") String travel,
#FormParam("start") String start,
#FormParam("duration") String end,
#FormParam("party") String people) {
String returnString = processInput(travel, start, end, people);
return "<body> " + returnString + " </body>";
}
Assuming that the REST services were correctly written and deployed, the problem here is the lack of understanding of the way a POST Rest Service is expected to behave as.
From the comment section above it is clear that you are trying to call a POST API directly from a browser.
That can be done fine for a GET type of a service but won't work for a POST type service.
Reason
The REST API uses several HTTP methods to perform various actions on REST resources. Any REST API that uses a GET call can be invoked using a web browser.
A post service however expects a certain set of input parameters (Here in your case, form params "travel", "start", "duration" and "party" are required)
You cannot call POST API's directly by simple typing the path of the Service URL in the browser.
You can use tools like POSTMAN, RESTer and a lot of such software available on the web, with extensive tutorials on how to use these for POST type REST API calls.

Sending a post request to REST API from controller in Playframework with Java

I'm new to playframework and to REST API.
I want to send a POST request to REST API in a controller.
What is the best way to do it? Does play have a support for it or do I have to use a plugin?
Basically I want it to look like this:
User submits a form.
I load a form data in a controller.
I send form data as a POST request
Get response, do something with it and display result
So far I'm stuck at point 3, I have no idea how to do this.
Code to visualize what I have in mind:
public static Result processForm() {
Form<FormData> myForm = Form.form(FormData.class).bindFromRequest();
String text = myForm.get().text;
//Send 'text' in a post request and get response
text = doSomethingWithResponse(response);
return ok(resultpage.render(text));
}
I don't think it matters but this is the API I want to use:
http://open.xerox.com/Services/fst-nlp-tools/Pages/API%20Docs
The following line of code sends a request and waits for a reponse:
WS.url(feedUrl).setHeader("Content-Type", "application/x-www-form-urlencoded").post("arg1=val1&arg2=val2").get().asJson();

Get the page that redirected you here, Spring MVC

I have the following problem. I want to use a controller, same for every page in my application. It is a common form included via include jsp in every page and it sends a mail to a predefined email account. The problem is, when I am posting the form, I get redirected to a blank page, with the url being my RequestMapping value despite the method called is actually void. So I need now to redirect me, after sending the mail to the page where I came from. How do I get access to the url link of the page that redirected me, into sending the email? Thanks
When returning void and one isn't handling writing the response yourself Spring MVC delegates detection of which view to render to a RequestToViewNameTranslator for which there is a single implementation the DefaultRequestToViewNameTranslator. Which basically takes the incoming URL, strips any suffixes (like .html etc.) and uses that as the viewname. The behavior you see now.
I guess you have 3 possible solutions
Add a hidden form attribute which contains the current page
Use the referer request header to determine where the request came from (not a 100% solution, See Alternative to "Referer" Header)
Submit the form through ajax so that you stay on the current page
For option 2 add the HttpServletRequest as a parameter to your request handling method and retrieve the header.
public String foo(HttpServletRequest request) {
String referer = request.getHeader("Referer");
return "redirect:" + referer;
}
I would probably go for option 3 and maybe add option 1 as a fallback when no javascript is available.

Is it a good practice to use asynchronous requests in this scenario?

I have a scenario that I have a button in JSP page which sends an email, the request is send to servlet asynchronously using jQuery Ajax and JSON, servlet searches in DB, if the user has an email, it returns the email address and sends an email to it, then forwards to the result page with success or fail of sending the email, but in a case that the user doesn't have an email, it returns false values using JSON to JSP and then a JSP form appears to the user to enter his email.
Is it good practice to use Ajax and I know that not each time there's a return value to the user or send request to servlet using get method which return a parameter in a case that the user doesn't have an email?
Using ajax is in practically all cases very good for User Experience. With ajax, the user will experience instant feedback without the need to face an annoying "flash of content" or a (partially) empty page because the whole HTML response needs to be generated/buffered by the server first. This is really a huge plus of using JS/ajax.
Using JSON is generally favorable above XML, HTML or even plain text. But there is no "best practice" with regard to the ajax data exchange format between client and server. Just pick whatever suits the requirement the best. JSON is perfectly fine for this case. jQuery understands it out-the-box and in Java you have choice of a plethora of easy-to-use JSON parsers.
However, when developing an ajax-enabled webapplication, you really need to take into account that the core functionality does not break when the client has JS disabled. This is called Unobtrusive JavaScript. Most of the searchbots, mobile browsers and textbased browsers don't use JS. You should try to use JS only for Progressive Enhancements. To test this yourself, in Firefox you can use for example the Web Developer Toolbar to easily enable/disable JS support. Run your website with JS disabled and observe if the core functionality is maintained as well.
The best way to achieve this is to start developing the website without any single line of JS code, even without a single onclick, onsubmit, onwhatever attribute on the HTML elements. Once you get the core functionality to work, then you can start adding JS in flavor of a script which executes during document ready and attachs functions to the HTML elements of interest (even here, you should not change the original HTML code!). Let the JS functions fire ajax requests on the same URL or maybe a different one, depending on the requirement. You can in the Servlet distinguish between an ajax and normal request as follows:
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Handle ajax request. Return JSON response here.
} else {
// Handle normal request. Return normal HTML response here (by JSP).
}
See also:
Simple calculator in JSP - contains unobtrusive JSP/Servlet/jQuery example
Json is just a data-interchange format. Using Json or not has nothing to do with using asynchronous communication or not... You can do both communication types using Json (or XML, or serialized objects, it doesn't matter).
Now, in your problem, it looks like you just want to use Asynchronous communication to improve the user experience (it will not flick the user's browser). If that's the case, Asynchronous communication is the way to go!
I don't think you need ot use AJAX in this.
The main idea of the ajax is to render server response without postback and in your case you are redirecting page after you get some kind of result.
In my opinion you shoul choose on of these two ways.
1) Use AJAX, send data to servlet and then render response from server wether the mail is sent or not.
2) Submit your form to servlet and sent email and then redirect to jsp with the success/fail result.
Hope it helps.

Using ajax to call a servlet

As I understand it and have used it, AJAX is used to make requests from the client to the server and to then update a HTML DIV on the client with new content.
However, I want to use AJAX from a client to a servlet to verify the existence of a URL. If the result is bad, I can set an error message in the servlet and return it to the client page for display.
But does anyone know if, in the case of a positive result, I can have my servlet automatically display another (the next) page to the user? Or should that request be triggered by Javascript on the client when the positive results is received.
Thanks
Mr Morgan.
Since your ajax call is executed in the background the result returned by the servlet, returns to the ajax call, which should then act accordingly to the result. e.g. trigger the display of another page. (Which could have been already in the ajax response and then you can show it in a div or iframe or ...)
As per the W3 specification, XMLHttpRequest forces the webbrowser to the new location when the server returns a fullworthy 301/302 redirect and the Same Origin Policy of the new request is met. This however fails in certain browsers like certain Google Chrome versions.
To achieve best crossbrowser result, also when the redirected URL doesn't met the Same Origin Policy rules, you would like to change the location in JavaScript side instead. You can eventually let your servlet send the status and the desired new URL. E.g.
Map<String, Object> map = new HashMap<String, Object>();
map.put("redirect", true);
map.put("location", "http://stackoverflow.com");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
resposne.getWriter().write(new Gson().toJson(map));
(that Gson is by the way Google Gson which eases converting Java Objects to JSON)
and then in the Ajax success callback handler in JS:
if (response.redirect) {
window.location = response.location;
}
In your success call back (on client), set the self.location.href to new URL.
HTML is a "pull" technology: Nothing gets displayed in the browser that the browser hasn't previously requested from the server.
Hence, you don't have a chance to "make the servlet automatically display a different page." You have to talk your browser (from JavaScript) into requesting a different page.

Categories

Resources