How to use OPTIONS HTTP method in Spark framework? - java

I am having difficulty understanding how can I return all methods that are allowed on my HTML page or on my embedded jetty-9.4.4.v20170414 server using Spark framework?
Java Spark code:
options("/panel/data/options", (request, response) -> request
.headers("Access-Control-Request-Method"));
AngularJS code:
$scope.options = function(){
$http({
method: 'OPTIONS',
url: 'http://localhost:4567/panel/data/options',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function succesCallback(response){
alert(response.data)
});
};
This is what I have so far.

First, your Spark java method is modifying the request headers, it should only modify the response headers as your clients are not going to get back the modified request.
options("/panel/data/options", (request, response) -> response
.headers("Access-Control-Request-Method"));
Then in your angular method, as the back end is changing the headers of your response, then you should read those headers, not the data:
$scope.options = function(){
$http({
method: 'OPTIONS',
url: 'http://localhost:4567/panel/data/options',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function succesCallback(response){
alert(response.headers)
});
};

Related

Axios. Spring MVC returns a 415 response

I am using Vue.js, axios and Spring.
On the page I have the following axios code
axios({
method: 'post',
url: '/user/info',
params: {
'_csrf' : document.getElementById('csrf_id').value,
'name' : 'job',
'age' : '25',
},
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
And on the server I have a receiving method like this
#Controller
#RequestMapping("/user")
public class UserInfo {
#ResponseBody
#PostMapping(value = "/info", consumes = "application/x-www-form-urlencoded", produces = "application/json" + ";charset=utf8")
public String info(#RequestParam(value = "name") String name, #RequestParam(value = "age") String age) {
System.out.println(name);
System.out.println(age);
return "ok";
}
}
Axios makes a request to the server, but the server returns a 415 response.
The request headers are missing the application/x-www-form-urlencoded content type. I suspect the problem lies precisely in this.
Tell me, what am I doing wrong?
HttpMethod Post is a method of writing and transmitting data in the request body.
In your case, you put data through params. If you execute code as you write, data will be sent such as /user/info?_csrf=value&name=job&age=25 and there will be no data in the request body.
To get the response you want, you can modify it as below.
axios({
method: 'post',
url: '/user/info',
data: '_csrf=csrf&name=job&age=25',
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
change params keyword to data and write data like querystring.

JQuery.ajax error 400 bad request with Struts

I have a website, made with Struts1, java and JSPs, and I need to get datas from a webservice dynamically.
I call my java method using AJAX in my JSP, but I get an Error 400: bad request no matter what I try.
So here is my Javascript function in my JSP:
var panierSansFares=new Array();
function myFunction(){
$.ajax({
url: "myPath/getFares.do?method=doGet",
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8", // this
data: 'panierSansFares='+JSON.stringify(panierSansFares),
success: function(res) {
alert(res);
}
});
}
Note that panierSansFares in an array of objects, and it is not empty when the function is called.
And in my STRUTS, the action:
<action path="/getFares"
type="myPath.GetFaresServlet"
scope="request" >
</action>
And lastly, my java code:
public class GetFaresServlet extends Action {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response, ActionMapping actionMapping) throws IOException {
/**Some stuff**/
}
}
My Error 400 comes from the Struts, because I can see a "Invalid path was requested" error in Chrome developer tools (network tab).
I tried to bypass Struts and just call my java directly as a servlet, but I couldn't do it, I got error404.
I've never used ajax with Struts before so I'm lacking knowledge to find where the problem is.
Thank you
I did not understand your problem but i follow this code for api call
function APICall(url, methodType, data) {
var d = $.Deferred();
methodType = methodType || "GET";
data = data || null;
$.ajax({
url: url,
async: true,
method: methodType,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response, status, request) {
d.resolve(response, status, request);
},
error: function (error) {
d.resolve(error.responseJSON);
}
});
return d.promise();
}
APICall(url, methodType, data).done(function (response, status, request) {
d.resolve(response, status, request);
}).fail(function (response) {
d.resolve(response, status, request);
});

Spring REST API, Pass a primitive type to the controller

#CrossOrigin(origins = "http://localhost:3000")
#GetMapping("")
public ResponseEntity<List<ToDoItemViewModel>> loadCategoriesByName(#RequestParam(required = false) String name)
{
List<ToDoItemViewModel> allItemsByCategoryName = toDoItemService.getAllItemsByCategoryName(name);
return new ResponseEntity<>(allItemsByCategoryName, HttpStatus.OK);
}
How can i pass just a primitive type to the controller, here is how my $.ajax looks like
$.ajax({
method: 'GET',
url: "http://localhost:8080/todItems",
contentType: 'application/json',
crossDomain: true,
data: 'Work',
success: (resp) => {
console.log(resp)
},
error: (resp) => {
console.log(resp);
}
})
Now when i debug it, it indeed sends the request to this controller, but the String name is always null for some reason, can you just show me what i have to adjust in my ajax request, it's probably something in the data field.
You are using GET Request with request params(#RequestParam annotation).
#RequestParam means that param in request pass across url, like this;
http://localhost:8080/todItems?name=Work
So, you just need to move data to url params.
If you prefer send data across request body, please do not use GET method, use POST instead. Many web servers are not supporting request body in GET Requests

Cookie not being passed on subsequent requests

I am having a problem with passing a cookie while trying to make subsequent requests with AJAX to my Spring MVC controller.
For e.g. I have a /login endpoint to which I pass some JSON via POST method and it sets the cookie. I see the cookie in the firebug:
As you can see it is there. I am creating a cookie like this:
NewCookie cookie = new NewCookie(new Cookie(SECURITY_TICKET, encodedTicket, configKey, null), null, (int) TimeUnit.MINUTES.toSeconds(expireTime), expireTimeDate, false, false)
And setting it to HTTP headers:
httpHeaders.add(HttpHeaders.SET_COOKIE, cookie.toString());
Then these headers are being added to ResponseEntity like this:
ResponseEntity entity = new ResponseEntity<>(this.entity, this.httpHeaders, this.status)
And this response entity is returned. My conroller's methods are all REST based.
So then I am trying to call the other (/search) endpoint after successful login which functionality is expecting the cookie and it obviosly fails because for some reason cookie is not being passed back.
My AJAX calls looks like this:
$(function () {
$.ajax({
url: 'http://localhost:8080/dev-citigroup-citi/login',
type: 'POST',
dataType: 'json',
data: '{ "username": "client1", "password": "*******", "platform": "iOS", "UUID": "321321321", "application": "CitiReach", "applicationVersion": "1.0" }',
success: function (data, status, xhr) {
$.ajax({
url: 'http://localhost:8080/dev-citigroup-citi/search/eventattendee?q=*:*&start=0&rows=1&wt=json&indent=true',
type: 'GET',
xhrFields: { withCredentials:true },
success: function (data, status, xhr) {
console.log(data);
},
error: function (jqXHR) {
console.log(jqXHR);
}
});
},
error: function (jqXHR) {
console.log(jqXHR);
}
});
});
As I mentioned the /login is OK but the other call fails. I am adding xhrFields: { withCredentials:true } which should be including the cookie in the /search request but for some reason it is not.
I also have CORS being set up correctly:
Access-Control-Allow-Origin: http://localhost:63342
Access-Control-Allow-Credentials: true
http://localhost:63342 is the origin where the request comes from, it is configured in the CORS headers.
Any idea what might be wrong here?
I found the solution, so rather than having xhrFields: { withCredentials:true } on the method level, I've put it globaly:
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
And cookie is passed now within the subsequent requests. No idea why it doesn't work on method level, maybe a bug in jquery...
jQuery version I was using: 2.1.3
Maybe this will help someone in future.

File Upload using ajax and jquery in spring

var urlUpload = "${root}manager/uploadFile.html";
var params = $('#topicForm').serialize();
$.ajax({
type: 'POST',
url: urlUpload,
data: params,
contentType: 'multipart/form-data',
processData: false,
success: function(data) {
alert("success");
}
});
#RequestMapping(value="/manager/uploadFile.html", method = RequestMethod.POST)
public String uploadFile(#ModelAttribute("topicForm") TopicForm topicForm,
#RequestParam("topicDoc") MultipartFile multipartFile ModelMap model) { ... }
I am getting the below exception
org.springframework.web.multipart.MultipartException: Could not parse
multipart servlet request; nested exception is
org.apache.commons.fileupload.FileUploadException: the request was
rejected because no multipart boundary was found.
The plugin is working fine thank you.
var urlUpload = "${root}manager/uploadFile.html?categoryId="+$("#category").val()+"&topicName="+$("#topicName").val();
$.ajaxFileUpload({
url:urlUpload,
secureuri:false,
fileElementId:'fileupload',
dataType: 'html',
success: function (data, status) {
alert("success");
}
});
The plugin is working fine, now i need to send few form fields to the controller along with the input file. in the above ajax call i appended the values to url. Is there any other solution for this?
The problem is that you're attempting to upload a URL-encoded serialization of the form, while claiming that it's multipart (see documentation of JQuery's serialize() function).
You need to use a plugin that will create the proper request. Here's one that I've used.
Alternatively, you can use HTML5 to upload files. I haven't done this.

Categories

Resources