Make Call to Back-end, Multiple Path Variables, Ext Js - java

I've got a RESTful call that I'd like to make to the back end of my application. The front end is written in Ext JS (JavaScript) the back-end in JAVA utilizing Hibernate. The application utilizes the MVC design pattern.
On the back end, I've got a GET request endpoint with a "mapping" akin to: thing/{thingOne}/otherThing/{thingTwo}.
Ext JS provides a number of functions on their stores for hitting a back end through a model's proxy: .load(), .save(), .remove(). Each of these is able to take multiple arguments for their [options] parameter; however, I am attempting to find documentation that shows me how to make a multi-parametered request to a back-end GET endpoint and have found none, so far.
My assumption is that the call would be structured like: .load("param1", "param2") based upon the documentation for .save() and .remove(). Here's the doc. for save, for remove, and load.
So, how do I make a GET call to the back end with multiple parameters? Am I even in the correct ballpark?

You can use "extraparams" on proxy.
sencha api 4.2.2 - extraparams on store
var formOperation = [];
var example = {"city":"Manchester"};
Ext.Object.merge(formOperacion,example);
store.getProxy().extraParams = formOperation;
store.load();
Another solution:
Sencha api - store - Dynamic Loading
store.load({
params: {
group: 3,
type: 'user'
},
callback: function(records, operation, success) {
// do something after the load finishes
},
scope: this
});

Build the request's URL as a concatenated string, including the arguments:
var requestUrl = 'thingOne/' + thingOneVar + '/otherThing/' + otherThingVar;
Note that whether your "built" string should be prefixed with a / depends upon how your model's proxy is configured. Essentially, you are aiming for a legitimate request url.
And make a request via the proxy (here, I'm using AJAX):
Ext.Ajax.request({
url : requestUrl,
// ....
});
The then needs to be handled by a callback or as a promise.

Related

React.js: POSTMapping fetch from JavaSpring-boot backend sends request, but does nothing

I'm the midst of creating a fullstack project consisting of a React-js frontend, a Java Spring-Boot backend, and an SQL database. I have a simple set of classes/interfaces/controllers set up for getting a list of objects in the database, as well as creating/deleting/modifying individual objects.
After linking the database and back-end and confirming all the controller requests were all functional, I tried to use them on the front-end. The GET requests all worked fine, but trying to use any request that required passing a request body did not seem to function. Here's how it went down:
Image 1
First, here's a POSTMapping request in the back-end. I am using Autowired for these requests.
const createNewIS = (e) => {
return fetch("http://localhost:8080/ideas/create", {
method: 'POST',
crossDomain: true,
headers: {
'Accept': 'nology-brainstorm/json',
'Content-Type': 'nology-brainstorm/json',
'API-Key': 'secret'
},
body: JSON.stringify({
"spaceid": 4,
"name": newISName,
"description": newISDesc
})
}).then((nothing) => {
updateNewISPopUp(e);
})
}
Second, here's the fetching function on the front-end. I have tried running this function without the API-Key header, without the .then() proceeding the first clause, and also without encapsulating the class's key names in speech marks. None of these seemed to have any effect, and the result was always as follows:
Image 2 (Browser Console)
The request seems to be made, and the body appears to have been successfully passed. But when I check the database or the state in my front-end that stores its retrieved objects, the new object is not added to it. Apologies if the solution is an obvious one here, but does anyone know why the request is not properly running? I have been looking at this for hours with no luck.
415 is Unsupported Media Type. This is generally related to your Content-Type
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
You are passing a custom content-type, therefore you need to define it on your backend controller as well.
#PostMapping(path = "users",
consumes = "nology-brainstorm/json",
produces = "nology-brainstorm/json")

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.

Spring, Angular JS and exception handling in the service layer

Our development team is building an application that uses jasper-reports 6.2.0, spring-mvc 3.2.14, java-ee-7, tomcat 8 and in the front-end we use angularjs. Our rest requisitions are all made via ajax.
The application is entirely built to receive json objects as response for our requisitions, because our requisitions via angularjs are all made via Ajax. In a specific application feature we have a regular get requisition using window.location = url, because we need to return a streaming which is nothing more than a byte array containing a PDF file content.
That being said, when we have a back-end error while generating this PDF file our application redirects user to a blank screen with a json object printed in it.
I've already had experience in spring-mvc exception handling globally ou per exception case, using exception handling with ExceptionHandler annotation or per ControllerAdvice to generalize the exception handling, but always handling classes in the controller layer annotated with Controller returning a ModelAndView object, but never classes in the service layer annotated with Service.
My question is how to capture a exception and make the application redirects users to a error screen with some parameterized message when we have regular get requisitions.
In my experience, and even if it's not exactly an answer to the question, main issue is not server side but client side :
stop doing window.location = url to download Content-Disposition:attachement files in an RIA application. Particularly when the download can cause errors thrown to the client. really.
Libs like fileDownload ( https://github.com/johnculviner/jquery.fileDownload ) allow to download the file in background, avoiding all the mess when an error append, and the UI freeze waiting for the server response.
So lets say you want to take care of exception on client side on the basis of http status code then you can make a interceptor like :
var app = angular.module('appname',[]);
app.factory('myHandler', function ($injector) {
var interceptor = {
response: function (response) {
.
.
.
return response;
},
responseError: function (response) {
if (response.status == 401) {
location.href = "#/error";
}
else if(response.status == 403){...}
else if().....
return response;
}
};
return interceptor;
});
and inject it in your application as :
app.config(function ( $injector) {
$httpProvider.interceptors.push('myHandler');
...
});
now every request would first go here , check if error status or whatever you want it to and then if no error (in which case you dont change location.href) it continues ,magically to wherever it was going else goes to specified templateURL on the basis of routeProvider.
Helpful links injector, httpProvider

Params for a GET request for a REST Service Java

I am creating a REST service in Java ,and have a doubt with regards to params for the GET method .
I have to pass the below params in a GET request
Function
"GET" File status :
Params:
Time Range:(String)
FlowId:(String)
ID_A= or ID_B= or Both (String)
IS_ADD_A= or IS_ADD_B= or both (String)
Regex=(String)
Cookie=XXXXX
So as there are 6 params,so passing it as a query string would not be an efficient way and can't but the same in body(as it is against the HTTP GET specification)
Making this as a POST call would be against the REST principle as I want to get data from the server ,
What would be an efficient way of solving this ,would passing the params as query string is out of question,passing it in body which is against the HTTP spec ,making this as headers which may also be not good ,making this as POST request which will voilate the fielding's REST principle .
Passing data in the body of an HTTP GET call is not only against the spec but causes problems with various server-side technologies which assume you don't need access to the body in a GET call. (Some client side frameworks also have some issues with GET and a query in the body) If you have queried with long parameters I'd go with POST. It's then using POST for getting data but you'd not be the only one having to go this way to support potentially large queries.
If your parameters values aren't very long, using query string is your best option here. 6 params is not a lot, as long you don't exceed the IE limit of characters in the path - 2,048 (http://www.boutell.com/newfaq/misc/urllength.html). For example Google search engine uses many more params then 6. If there is a possibility that the URL path will exceed the limit above, you should use POST instead.

How to configure Struts 2.3 to accept both GET and POST parameters?

We have migrated from 2.0 to 2.3. In Struts 2.0, we were able to send an AJAX request that contained both post and get parameters. But after migrating to Struts 2.3, were are not able to do such requests.
Here is what a sample AJAX request made using Prototype.js looks like :
var url = '/security/userdetails.action?mode=edit&userid=5';
var params = Form.serialize(form);
new Ajax.Request(url,
{
parameters: params,
onSuccess: function(trans) {
console.debug('success', trans);
},
onFailure: function(trans) {
console.debug('failure', trans);
},
onException:function(trans) {
console.debug('exception', trans);
}
});
As you can see, the above AJAX request contains both GET and POST requests. This worked fine with 2.0 but in 2.3, it seems the request is validated and the request is forwarded to result type "input", but for that we have no JSP configured, and in the end all we get is a 404 Not Found Error.
But if we change the code to the following, it works in Struts 2.3 as well
var url = '/security/userdetails.action?mode=edit'; // ------ The Changes are here
var params = Form.serialize(form);
params.userid = 5; // ----- And here
new Ajax.Request(url,
{
parameters: params,
onSuccess: function(trans) {
console.debug('success', trans);
},
onFailure: function(trans) {
console.debug('failure', trans);
},
onException:function(trans) {
console.debug('exception', trans);
}
});
What is wrong with the first method ? Is there a configuration in Struts 2.3 to allow that request to be made ?
It depends on how HttpServlet works and which method Struts2 uses to retrieve parameters from the request, and method GET/POST (not both) used during that. Struts2 uses request.getParameterMap() to get parameters
Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.
but you are using http post method and parameters should be post data.
The thing is this :
The userid was defined as an integer in the action class, so obviously the setter and getter for that was defined in terms of integer as well
But this userid, was present in both the url (as the query string) and in the post body - so basically an array of two strings. when the struts tries to parse the integer from the array, it gets the numberformatexception -> this results in invalid form submission and thus redirects to the "input" result type.
I did not see the struts log in that matter and got swayed away from the actual problem.
Thanks for your inputs though.

Categories

Resources