Android app submit throws Request method 'GET' not supported - java

I am new to app world and started building Android app using phonegap for my already available service which serves for my web users. i have my services build on java, spring mvc, and my controllers are capable of receiving json objects.
so kept that in mind. i have created basic login page with login button and i was trying to hit my backend services. i have below code
$('#login_btn').click(function() {
$.ajax({
url: "http://localhost:8080/myweb/user/signin",
type: "post",
crossDomain: true,
cache: false,
data: "userName=" + $("#username_txt").val() + '&password=' + $("#password_txt").val(),
dataType: "jsonp",
async: true,
success: function(data) {
alert("ok");
},
error : function(data){
alert("not ok");
}
});
my controller method accepts POST request, when i hit login button, i see my service giving me error as
HttpRequestMethodNotSupportedException: Request method 'GET' not
supported
and my error block getting executed.i dont what i am doing wrong here, thanks for your answers
EDIT-
my server side controller code
#RequestMapping(value = "/signin", method = RequestMethod.POST)
public #ResponseBody
ModelMap loginUser(#RequestParam(value = "userName") String userName, #RequestParam(value = "password") String password, HttpSession session, HttpServletRequest request) {}

Related

Get the file name for a document attached using AJAX on the JSP page

I have a JSP form where in one of the field I am uploading a document, say a notepad using an AJAX call and the upload is happening in a UNIX path. Now I need to see the name of the attached document on the jsp once the upload is successful. Please let me know how can I do it.
Ajax Call:
$.ajax({
type : 'POST',
url : '/test/actionToController/',
data: new FormData(document.getElementById("formNameInJSP")),
enctype: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
async: false,
success : function(result) {
},
error : function(result) {
console.log('ohh.. something happened in Document Upload');
}
});
Controller:
#RequestMapping(value = "/actionToController", headers=("content-
type=multipart/*"), method = RequestMethod.POST)
public String actionToController(#RequestParam("myFile")
CommonsMultipartFile[] fileUpload, HttpSession session)
throws JsonGenerationException, JsonMappingException, IOException {
/* Upload Code removed from here, its working fine */
docName = notepadTest.txt;
return "docName";
}
docName here has the name of the file which we need to see in the JSP page.
Thanks

How to correctly handle this AJAX request that send an array to a Spring MVC controller method? Why it can't work?

I am pretty new in Spring MVC and I have the following problem trying to handle an AJAX request that send an array of int to a controller method.
So I have the following situation. I have this JQuery function:
// It is global and it is initiazilized by another function:
var checkedRowList = new Array();
// SOME OTHER CODE THAT INIZIALIZED THE checkedRowList array here
...............................................
...............................................
...............................................
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: {'checkedRowList' : checkedRowList},
url: "validaProgetti"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
So the checkedRowList is correctly initizialized (I checked it) and I use the ajax() function to send it toward the validaProgetti resource using a POST request.
Then into a controller class I have this method that have to handle the previous request:
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public String validaProgetti(#RequestParam List<Integer> checkedRowList, Model model, HttpServletRequest request) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
As you can see it handle HTTP Post request toward the validaProgetti resource. And Inside it I have specify the RequestParam List checkedRowList to retry the array passed by the AJAX request.
But it don't work because when the AJAX request is performed it don't enter into the validaProgetti() method and it shown the alert("SUCCESS"); popup.
Why? What am I missing? How can I fix this situation?
as I see you missed two things.
The first one is that in the Spring Web MVC controller. You don't pass a RequestParam but RequestBody.
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
The second one is related with your Ajax request. You should send javascript array formatted as JSON. This is done via the function JSON.stringify(), which converts js value into json.
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: JSON.stringify(checkedRowList),
url: "validaProgetti",
contentType:"application/json"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
Also you may change the request mapping when defining in java code. Since it is a relative path, it would be confusing in some cases.
#RequestMapping(value = "/validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}

Http status 404 (Not Found) on jquery ajax GET to spring controller?

My spring controller contains such get handler :
#RequestMapping(value = "/country", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Region> getRegionsFor(#RequestParam(value = "countryName") String countryName,
#RequestParam(value = "geonameId") Long geonameId) {
logger.debug("fetching regions for {}, with geonameId {}", countryName, geonameId);
RegionInfo regionInfo = restTemplate.getForObject(
"http://api.geonames.org/childrenJSON?geonameId={geonameId}&username=geonameUser2014",
RegionInfo.class, geonameId);
return regionInfo.getRegions();
}
#Controller is mapped to /hostel. So url is /hostel/country?countryName=%27&Albania%27&&geonameId=783754
When I type in chrome browser
http://localhost:8080/HostMe/hostel/country?countryName=%27Albania%27&geonameId=783754
It returns json response as expected!!!
But I want to access this url with the following ajax call made with jquery:
$.ajax({
headers : {
'Accept' : 'application/json'
},
url : '/hostel/country',
dataType : 'json',
data : {countryName:"Albania",geonameId:783754},
type : 'GET',
async : true,
success : function(response) {
console.log("response=" + response.join(','));
},
error : function(errorData) {
console.log("data on fail ");
printObject(errorData);
}
});
As you guess this doesn't work at all. Http status 404 (Not Found) is returned to error: handler .
How can I solve this?
The url in the ajax call is relative to the hostname. You need to add your web application context
url : '/HostMe/hostel/country',

Getting exception in JQuery file uploader

I am new to JQuery file uploader and I am implementing some part of that. When I select an image from JQuery file uploader, a call goes to server side (SpringController) but the API returns:
406 Not Acceptable
this my call to server:
$(this).fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: uploadSettings.upload_url,
type: 'POST',
maxNumberOfFiles: uploadSettings.maxNumberOfFiles,
maxFileSize: uploadSettings.maxFileSize,
acceptFileTypes: uploadSettings.fileSelection,
sequentialUploads: true,
paramName:'uploadfiles[]',
dataType: 'text'
});
and my Java Controller code is as:
#RequestMapping(value = { "/user/fileuploader" }, method = RequestMethod.POST,
produces = "text/plain")
#ResponseBody public String uploadFileHandler(
#RequestParam("uploadfiles[]") MultipartFile[] file,
HttpServletRequest request, HttpServletResponse response) {
Any advice?
Here is a project that uses a very similar stack to JHipster (I'm the author of both projects), and which does uploading with the same JQuery plugin:
https://github.com/ippontech/tatami/blob/master/src/main/java/fr/ippon/tatami/web/fileupload/FileController.java#L193
As you can see my return object is different. You can copy my code from:
https://github.com/ippontech/tatami/tree/master/src/main/java/fr/ippon/tatami/web/fileupload

Spring MVC. Redirect page

I have a controller wich handles URL studentEdit.html. When I pass to controller value 'get' using AJAX I need to redirect to another page viewStudents.html, but nothing happens. I stay on the same page. The method returns the ModelAndView, but why it does not redirect to another page I do not know.
I also tried to set url as:
redirect:viewStudents.html and redirect:viewStudents
but it did not helped.
#RequestMapping(value = "/studentEdit.html", method = RequestMethod.GET)
public ModelAndView getStudentProfile(#RequestParam(value = "get", required = false) String get) {
if(get != null && get.equals("get")) {
return new ModelAndView("redirect:/viewStudents.html");
} else {
ModelAndView mav = new ModelAndView("studentEdit");
return mav;
}
}
function getStudent() {
$.ajax({
type: "GET",
url: "/IRSystem/studentProfileEdit.html",
data: "get=" + 'get',
success: function(response) {
},
error: function(e) {
alert('Error' + e);
}
});
}
I would appreciate any information, thank you.
If you want to redirect to another page after request, there is no need to use AJAX.
A simple link should be enough:
click me
What happens when you click on the link:
a GET request to /IRSystem/studentProfileEdit.html is performed
get=get is passed as request data
by default, user is redirected to link's href (i.e /IRSystem/studentProfileEdit.html), but you can redirect him somewhere else
Assuming the rest of your code is correct, using <a> as mentioned above together with redirect:/viewStudents.html should redirect as desired.
Also check the docs about redirect: prefix to make sure your redirect is interpreted correctly.

Categories