Sending data to spring controller using AJAX - java

I know that this question has been asked many times, but I have looked at every variation I could find and have still not been able to find out my issue.
Here is my ajax call:
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
contentType: "application/json",
data: JSON.stringify(input),
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
The endpoint works. You can take my word for it.
Spring controller:
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
And here is my model class:
public class FormInput {
private String userInputOne;
private String userInputTwo;
private String userInputThree;
private String userInputFour;
private String userInputFive;
public FormInput(String userInputOne, String userInputTwo, String userInputThree, String userInputFour, String userInputFive) {
this.userInputOne = userInputOne;
this.userInputTwo = userInputTwo;
this.userInputThree = userInputThree;
this.userInputFour = userInputFour;
this.userInputFive = userInputFive;
}
public String getUserInputOne() {
return this.userInputOne;
}
public String getUserInputTwo() {
return this.userInputTwo;
}
public String getUserInputThree() {
return this.userInputThree;
}
public String getUserInputFour() {
return this.userInputFour;
}
public String getUserInputFive() {
return this.userInputFive;
}
}
I keep getting a HTTP status code of 415, which means unsupported media type. I set the contentType to "application/json", and I also tried to add "consumes= 'application/json'" to my Spring controller and that didn't help either. Thank you for any help you can give.
EDIT: I am now getting the following error after changing RequestMethod.GET to RequestMethod.POST: "Error 405: Request method 'GET' not supported"

There is no need to send parameter as json,you have made things complicated
In javascript code,you can remove contentType: "application/json", and change the format of data property to send data directly
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
//contentType: "application/json",
data: input,//send data directly
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
In java code,you can remove #ResponseBody annotation before FormInput
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}

The java controller method you have written is of type 'GET', it should be changed to 'POST', as the ajax call you are making is also of type POST
Try this and it will work
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}

I guess main problem in not match http methods. You sent by POST method, but controller wait for GET method.

This is because your method signature doesn't match. Just remove contentType: "application/json".

Related

my ajax wont execute my controller

i tried accessing my controller through ajax to get DB results but it wont work. The ajax is inside a submit button and executes well without the ajax. The code is supposed to execute a query and check if the input exists.
Here's my ajax
var jsonData = {
"appname": appname,
"txtype": txtype,
"ipaddress": ipaddress
};
$.ajax({
type: 'POST',
url: "checkaccesspermission.html",
data: jsonData,
success: function(data) {
if(data == "exists"){
alert('Permission Already Exists!');
return false;
}else{
alert('Add Permission test Succesful!');
return true;
}
},
async: false
});
here's my controller
#RequestMapping(value="/checkaccesspermission", method=RequestMethod.GET)
public String checkaccesspermission(#ModelAttribute("loginForm") IpAccessManagementModel loginForm, Model model,
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID) throws IOException{
System.out.println("CHECKACCESSPERMISSIONs");
IpAccessManagementModel sub = new IpAccessManagementModel();
//System.out.println("<script language='JavaScript'>alert('Hello');</script>");
sub.setAppName(appID);
sub.setTxtType(txtype);
sub.setIpAddress(ipaddress);
System.out.println(ipaddress);
ipAccessMGTDAO.addPermission(sub);
String resultCheckExist = ipAccessMGTDAO.checkAccessPermission(sub);
return resultCheckExist;
}
Remove the .html extension and Change your method annotation in the controller to method=RequestMethod.POST
also remove
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID
because its a Post request

Pass model and a string using ajax to Spring MVC

Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.

Spring MVC 3.2 +Jackson

My requirement is simple i.e i want to write a common methods which suppose to have auto intelligence based on user request it will generate response, like if i submit as a html it should produce html . if i submit as a Json it should produce Json.
Below is 2 sample code ,If i write 2 separate method it works fine but i want to write it to one common method.
1)below is sample code which works for html
#Controller
public class Program1Controller {
#RequestMapping("/helloworld")
public #ResponseBody ModelAndView helloWord(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
2)below is sample code which work for json
#RequestMapping(value = DUMMY_EMP, method = RequestMethod.GET)
public #ResponseBody String getDummyEmployee() {
String message = "Welcome to TEST";
return message;
}
Instead writing 2 separate method i want to write one method which should have auto intelligence to send a response based on user request.
Above Query for GET ,Same also how can i do for POST.
You can handle that one in ajax. In your controller you have 2 different methods returning JSON, POST and GET and it can have the same value for its RequestMapping. Example:
#RequestMapping(value = "/returnJSON", method = RequestMethod.GET)
public #ResponseBody String getDummyEmployee() {
String message = "Welcome to TEST";
return message;
}
#RequestMapping(value = "/returnJSON", method = RequestMethod.POST)
public #ResponseBody String getDummyEmployee2() {
String message = "Welcome to TEST";
return message;
}
This should also be done for the one returning the HTML Object:
#RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public #ResponseBody ModelAndView helloWord(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
#RequestMapping(value = "/helloworld", method = RequestMethod.POST)
public #ResponseBody ModelAndView helloWord2(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
Now, before going to the jquery ajax call, pass as parameter the url and type:
$.ajax({
type: type,
url: url,
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});

Call java method with JQuery

I developed a message system and in the inbox I want to delete multiple messages selecting it with some checks and calling the delete method but I don't know if I can do it witout a form. Some people tells me that I can do with JQuery but I don't know how to do.
MessagesController.java
#RequestMapping(value = "/mensajes/delete/{menssageId}")
public String menssagesDelete(final ModelMap model, #PathVariable("menssageId") final Integer mensajeId,
final HttpServletRequest request, final RedirectAttributes redirectAttrs) {
final User user = (User) request.getSession().getAttribute(Constantes.SESSION_USER_KEY);
final Mensajes mensaje = this.mensajesService.loadMensaje(mensajeId);
this.mensajesService.deleteMensaje(mensaje);
return "redirect:/menssages/home";
}
EDIT:
Now I have this:
MessagesController.java
#ResponseBody
#RequestMapping(value = "/mensajes/deleteMensajes.json", method = RequestMethod.GET, headers = "Accept=application/json")
public void deleteMensajes(final String[] arrayMensajes) {
}
And this is de js code:
function eliminarMensajes(){
var arrayMensajesSeleccionados = jQuery('[name="msgIdRecibido"]:checked').map(function () {
return this.value;
}).get();
//Llamada ajax
$.ajax({
type: "GET",
url: "deleteMensajes.json",
data:{'arrayMensajes': arrayMensajesSeleccionados},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("hola");
}
});
When enter the controller method the arrayMensajes is null What Im doing wrong?
It works when add this to controller
public void deleteMensajes(#RequestParam(value="arrayMensajes[]", required=false) final String[] arrayMensajes)

Java Passing array via jquery

i have action below
#RequestMapping(value = "info_pure", method = RequestMethod.GET)
public ModelAndView GetInfo(String ser_name, String[] p_input_week_days, int p_input_month_day) {
ModelAndView mav = new ModelAndView(JspView.PureInfoAup);
String aaa = request.getParameter("p_input_week_days");
i send get request to this action via jquery ajax.
var myarray = ['Element 1', 'Element 2', 'Element 3'];
var dataobject = {
ser_name: p_ser_name.trim(), p_input_week_days: myarray, p_input_month_day: p_month_day
};
$.ajax({
url: '../info_pure',
data: dataobject,
type: 'GET',
success: function(data) { /// go forward
but when request send it give me an error. it says that my array parameter is null
here is my result on firebug
Use Spring MVC #RequestParam annotation.
#RequestMapping(value = "info_pure", method = RequestMethod.GET)
public ModelAndView GetInfo(#RequestParam("p_input_week_days[]") String[] days) {
String[] aaa = days;
More details: http://docs.spring.io/spring/docs/4.0.0.RC1/spring-framework-reference/html/mvc.html#mvc-ann-requestparam
I had solved this problem using Google Gson library.
Update your controller method like this
#RequestMapping(value = "info_pure", method = RequestMethod.GET)
public ModelAndView GetInfo(String ser_name, String p_input_week_days, int p_input_month_day) {
Gson gson=new Gson();
String[] weeks=gson.fromJson(p_input_week_days, String[].class);
// ....
Update your Ajax call like this
var myarray = ['Element 1', 'Element 2', 'Element 3'];
var dataobject = {
ser_name: p_ser_name.trim(), p_input_week_days: JSON.stringify(myarray), p_input_month_day: p_month_day
};
$.ajax({
url: '../info_pure',
data: dataobject,
type: 'GET',
success: function(data) { /// go forward

Categories

Resources