I have such method in my controller
#Controller
#RequestMapping ("/admin/users")
public class AdminUserController {
..
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public #ResponseBody boolean deleteUser(#PathVariable("id") int id,
HttpServletResponse response) {
..
}
..
}
and this is ajax request
$.ajax({
url: '/admin/users/'+id,
type: 'delete',
success: function(data){
console.log(data);
},
error: function(e){
console.log(e);
}
});
When I send this request, it's fails and I get 405. When I looked at response header I saw this Allow:"GET".
Ok. I change in ajax request 'delete' to 'get' but then I get in response Allow:"DELETE" ..
What it can be?
I think that DELETE actions are not allowed by your server security configurations, and basically the header:
ALLOW: GET
is suggesting you to try a GET request instead, but since you specified
method = RequestMethod.DELETE
Spring in rejecting that GET invocation to the method.
you should change method = RequestMethod.DELETE to method = RequestMethod.GET
and issue an HTTP GET request.
Let me know if this helps.
Related
I having problem changing pages. So what I have is a button and when that user press that button a ajax Post is called. Here the example:
$.ajax({
contentType: "application/json",
type: "POST",
data: JSON.stringify(project),
url: "/saveProject",
success: function (data) {
console.log('done');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error while post');
}
});
#RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public #ResponseBody
String saveProject(#RequestBody Project newProject, Authentication authentication) {
projectService.saveProjectNew(newProject, authentication);
return "mywork.html";
}
So in the end I want to be redirect to mywork.html from the page I'm currently on. However nothing happens and I stay on same page. I'm probably missing something that I don't know. Quiet new to this.
To redirect the page into the mywork.html
You need to write the code once you get the response from the Ajax call
So under the success function of Ajax you should use
windows.location.href = "Your context path"+"/mywork.html";
Please refer the reference code below:
$.ajax({
contentType: "application/json",
type: "POST",
data: JSON.stringify(project),
url: "/saveProject",
success: function (data) {
windows.location.href = "Your context path"+"/mywork.html";
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error while post');
}
});
Here the spring web client code will not divert the call to the mywork.html.
All the call will be diverted only through the Ajax call.
return "mywork.html";
This code is only used to model your response which been retrieved after calling the endpoint.
Http redirection could be triggered from both the back-end as well as the front-end ajax code that you have posted.
For the redirection to work from the ui , you can add the window redirection like #Anurag pointed out in his answer on the ajax success callback.
But in your example you are trying to redirect the user to a new page from the backend endpoint itself. So provided that you already have a controller returning the view for the mapping /mywork.html in order for the redirect to work from the spring backend side , you need to do the following :
#RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public String saveProject(#RequestBody Project newProject, Authentication authentication) {
projectService.saveProjectNew(newProject, authentication);
return "redirect:/mywork.html";
}
or using ResponseEntity like :
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
In your code you were using the annotation #ResponseBody for the controller method which basically makes the endpoint a rest endpoint returning json by default. So , for redirection to work remove the annotation and make it a normal controller method returning view.
Still if you want to redirect from a rest endpoint then use HttpServletResponse like :
#RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public #ResponseBody String saveProject(#RequestBody Project newProject, Authentication authentication, HttpServletResponse response) {
projectService.saveProjectNew(newProject, authentication);
response.sendRedirect("url-here");
}
For more information Link.
I need to make a simple upload, just to send some files to the back end from the front end. But for some odd reason I can't make a POST request.
When I make a GET request, the controller is called and the simple printing that I have in it executes.
But when I create a POST request with which I wish to send the file to the back end, all that happens is that the request is created, the java code/Spring controller is not executed, not called. But the request returns with a success, and the callback function is executed.
Here is the controller, its supper simple. Nothing serious because I can't even get it to execute.
#RequestMapping(value = "/testingPost", method = RequestMethod.POST)
public void postTest(final HttpServletRequest pRequest, final HttpServletResponse pResponse){
#RequestMapping(value = "/testingPost", method = RequestMethod.POST)
public void postTest(final HttpServletRequest pRequest, final HttpServletResponse pResponse){
System.out.println("TESTING....POSST.........................................................................................");
}
And here is the Javascript snipped from the controller.
var data = {
testing: 'testInfo'
};
var config = {
'Content-Type': 'application/json; charset=UTF-8'
};
$http.post(urlBuilder.create("/S/S/S/" + "usglGed" + "/" + "testingPost"), angular.toJson(data), config)
.
then(function(response){
console.log("in success post");
}, function(response){
console.log("in fail");
});
Again nothing special. And I have no clue as to why spring controller is not executing the method. I'm not sure if there is some configuration in the project. Or I'm just not experienced enough, and I'm not seeing something.
Thank you in advance!
I am doing a servlet call from my ajax . How i can get the response in my ajax function as a variable .
function myajaxcall(name) {
var url = "/myServlet?name="+name
$.ajax({
type: 'GET',
url: url,
success: function() {
console.log("Success");
// also i want to get response from header which i have set in my servlet class . and call a another javascript method
// call a another javascript method by passing the response from servlet .
}
});
}
The Servlet code is :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String code=request.getParameter("name")+"Hi";
response.addHeader("code", code);
}
Now i want to use my "code" variable in ajax call so that i can send that to another javascript method ..
Thanks in advance .
As outlined in the jQuery documentation, the success setting for jQuery's $.ajax() function is a function, or array of functions, which has up to three parameters (and is subsequently passed three arguments when called after the AJAX request returns a successful response):
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
As you can see, the third parameter is of type jqXHR, which has a getResponseHeader() function.
Something like this should work (though untested):
$.ajax({
type: 'GET',
url: url,
success: function(data, status, xhr) {
var code = xhr.getResponseHeader('code');
yourFunction(code);
console.log("Success");
}
});
I have a javascript array that holds a couple of ids. I want to send it to a rest webservice that I have written. Here is the code that I have for that -
$.ajax({
type : 'GET',
url : 'http://localhost:portNo/GlassdoorWebProject/index/getJobsData/list/',
crossDomain : true,
data : JSON.stringify(allIds),
contentType: "application/json",
success : function(data){
alert("success in call2");
},
error : function(XMLHttpRequest,textStatus, errorThrown) {
alert("error");
}
});
When I execute this code I am getting an alert box that says error. This is how the method in my web service looks like -
#RequestMapping(value = "/getJobsData/list/{ids}", method = RequestMethod.GET)
public List<JobDetails> getJobs(#PathVariable("ids") String jobIds) {
System.out.println("ids"+jobIds);
return jobService.getJobDataForIds(jobIds);
}
When I run the it in a browser with the url in the browser it works. But when I run it through the code it does not work. Any suggestions?
Use this code snippet
#RequestMapping(value = "/getJobsData/list/", method = RequestMethod.GET)
public List<JobDetails> getJobs(#RequestParam("ids") String jobIds) {
System.out.println("ids"+jobIds);
return jobService.getJobDataForIds(jobIds);
}
the main problem is that you are sending the ids as the request parameters, but your are looking the values from the url. So i changed the code of your web service and i think it will solve your problem.
I have a web application running on Spring MVC using RESTful web services. I'm trying to send a JSON to those web services from an HTML/Javascript file. Here's the Javascript:
$.ajax
(
{
type: "post",
data: JSON.stringify(data),
contentType : "application/json",
dataType: "json",
url: "http://localhost/proj/service",
success: function(data)
{
callback(data);
}
}
);
And the mapping in Spring MVC:
#RequestMapping(value = "/proj/service/", method = RequestMethod.POST)
public ModelAndView procRequest(#RequestBody String paramsJson, HttpServletResponse resp, WebRequest request_p){
resp.setStatus(HttpStatus.CREATED.value());
resp.setHeader("Location", request_p.getContextPath() + "/proj/service");
resp.addHeader("Access-Control-Allow-Origin", "*");
//Code
}
For some reason when I delete the contentType key from the ajax request it goes through, but of course it is in an incorrect format since I expect the Javascript to send me a JSON string. But for some reason if I leave the contentType key I get the following error:
XMLHttpRequest cannot load http://localhost:8080/proj/service/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
I don't know what could possibly be causing this error since the appropiate header is there.
Thanks.
The Content-Type header triggers a CORS preflight request. You need to modify your handler to respond to an OPTIONS request with the following headers:
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
resp.addHeader("Access-Control-Allow-Headers", "Content-Type");
This should send the appropriate response to the preflight request, after which the browser will issue the actual request. You can learn more about preflight requests here: http://www.html5rocks.com/en/tutorials/cors/
I do it like this:
#RequestMapping("/listActions")
public #ResponseBody List<Action> list(HttpServletRequest request, HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
List<Action> actions = new ArrayList<Action>();
actions.add(new Action(1, "Do something fantastic"));
actions.add(new Action(2, "Save the world"));
actions.add(new Action(3, "Buy beer"));
actions.add(new Action(4, "Butcher a hog"));
return actions;
}