Post not executed on back end - javascript

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!

Related

Changing pages spring boot application

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.

How to redirect/forward to a new html page with variable content?

The problem
I'm creating a web app where the user is served a login page, login.html, and has to enter his credentials. The servlet class grabs the information using ajax in the form of a POST request, generated by the user clicking the submit button. After checking the correctness of the credentials, i wish to serve the user with a new HTML page, a welcome page, where the response of the servlet is transferred. The problem i'm facing is how to transfer the response from a starting LoginServlet class to a WelcomeServlet all the meanwhile, the client is projecting a new HTML page, welcome.html, and catch the response of the WelcomeServlet in an ajax call made by a js script in the new HTML page.
Background
I'm just starting to delve into the development of web-apps, so if i'm mistaken in any part of my logic and understanding of the whole frontend-to-backend process, please say so. I'm aware of the redirect() and forward() functions but i'm not understanding the way these functions can be used in conjunction, or the complete difference, with the client side of things.
I have the following servlets:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("welcomeservlet");
dispatcher.forward(request, response);
}
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//parse request and send response
}
In the login.html file i've included the following js code:
function loadNewPage() {
// retrieve data and store them in a js Object
$.ajax({
url: "loginservlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(jsObject),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
window.location.href = "welcome.html";
},
error: function (data, status, er) {
alert("error: " + data.text + " status: " + status + " er:" + er);
}
});
}
I'm not including another js script which would be placed inside the welcome.html purposely since i don't know what would i have to add in there to catch the response of the new servlet. A possible reason why this whole thing isn't working could be that i'm missing something in the functionality of the forward() function but couldn't find an example online that does the exact thing that i want to do.
(Image credit w3schools)
The fact is you can't jump to another servlet. Ajax response will be sent back to the same webpage from which request was generated.
For your requirement what you can do is, Check whether login is success or not in LoginServlet. If yes create a token, save it in database along with the username and send the same token as response to the client.
Now in client save the token in localStorage and redirect to welcome.html.
On welcome.html page loading check whether token saved in localStorage exists or not. If yes, check whether it's valid or not. If valid the call WelcomeServlet . Else display login screen.
It's called token based authentication. You can read more about it here

strange behavior of request methods while ajax request

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.

Correct way of making POST request with JSON in SPRING MVC?

I am fairly new to spring and want to the correct way of making post request. I have a list of json object that I want to post to my server
for example
var list = [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
I am making a post request in google closure using xhr to my server in this fashion
model.xhrPost(id,url,"list="+JSON.stringify(this.list),callback);
This is what my controller looks like
#RequestMapping(value={"/getInput"}, method = RequestMethod.POST)
#ResponseBody
public String logClientError(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception{
JSONObject result = new JSONObject();
try{
String errorObj = request.getParameter("list");
JSONArray errors = new JSONArray(errorObj);
some more code here which loops through the list...
result.put("isSuccess", true);
return result.toString();
}catch(JSONException e){
result.put("isSuccess", false);
return result.toString();
}
}
So in short I am making a post request by passing querystring parameter. Is this the correct way or should the content be posted in the body? If I post in the body what changes do I have to make ?
This is definitely not how you should post the data to REST endpoint. Going this way you can use GET instead of POST and it will work as well. However POST should be definitely used to create new resource and the content should be carried in message body not as a query param.
On the backend side you can catch and parse the content yourself or create a class (see below) that will be filled with data from body.
DTO:
class Person {
String name
Integer age
}
class PersonList {
List<Person> persons
}
Endpoint:
public String logClientError(#RequestBody PersonList list, HttpServletRequest request, HttpServletResponse response) throws Exception
Body:
{
"persons": [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
}
#ResponseBody can be used in the same manner for responses.

How to send javascript array to a rest service

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.

Categories

Resources