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
Related
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".
Am new to spring currently am trying to do HTTP POST request application/x-www-form-url encoded but when i keep this in my headers then spring not recognizing it and saying 415 Unsupported Media Type
for x-www-form-urlencoded
org.springframework.web.HttpMediaTypeNotSupportedException: Content
type 'application/x-www-form-urlencoded' not supported
Can any one know how to solve it? please comment me.
An example of my controller is:
#RequestMapping(
value = "/patientdetails",
method = RequestMethod.POST,
headers="Accept=application/x-www-form-urlencoded")
public #ResponseBody List<PatientProfileDto> getPatientDetails(
#RequestBody PatientProfileDto name
) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
list = service.getPatient(name);
return list;
}
The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this
we must remove the #RequestBody annotation.
Then try the following:
#RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public #ResponseBody List<PatientProfileDto> getPatientDetails(
PatientProfileDto name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
list = service.getPatient(name);
return list;
}
Note that removed the annotation #RequestBody
you should replace #RequestBody with #RequestParam, and do not accept parameters with a java entity.
Then you controller is probably like this:
#RequestMapping(value = "/patientdetails", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public #ResponseBody List<PatientProfileDto> getPatientDetails(
#RequestParam Map<String, String> name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
...
PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
...
list = service.getPatient(patientProfileDto);
return list;
}
The solution can be found here https://github.com/spring-projects/spring-framework/issues/22734
you can create two separate post request mappings. For example.
#PostMapping(path = "/test", consumes = "application/json")
public String test(#RequestBody User user) {
return user.toString();
}
#PostMapping(path = "/test", consumes = "application/x-www-form-urlencoded")
public String test(User user) {
return user.toString();
}
Remove #ResponseBody annotation from your use parameters in method. Like this;
#Autowired
ProjectService projectService;
#RequestMapping(path = "/add", method = RequestMethod.POST)
public ResponseEntity<Project> createNewProject(Project newProject){
Project project = projectService.save(newProject);
return new ResponseEntity<Project>(project,HttpStatus.CREATED);
}
The easiest thing to do is to set the content type of your ajax request to "application/json; charset=utf-8" and then let your API method consume JSON. Like this:
var basicInfo = JSON.stringify({
firstName: playerProfile.firstName(),
lastName: playerProfile.lastName(),
gender: playerProfile.gender(),
address: playerProfile.address(),
country: playerProfile.country(),
bio: playerProfile.bio()
});
$.ajax({
url: "http://localhost:8080/social/profile/update",
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: basicInfo,
success: function(data) {
// ...
}
});
#RequestMapping(
value = "/profile/update",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> UpdateUserProfile(
#RequestBody User usersNewDetails,
HttpServletRequest request,
HttpServletResponse response
) {
// ...
}
I guess the problem is that Spring Boot has issues submitting form data which is not JSON via ajax request.
Note: the default content type for ajax is "application/x-www-form-urlencoded".
replace contentType : "application/x-www-form-urlencoded", by dataType : "text" as wildfly 11 doesn't support mentioned contenttype..
You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.
#RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"})
It would be helpful if you posted your code.
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)
I have the page about.ftl which is invoked when I type localhost:8080/ui/about
and I have put the following block of code inside. Through SendToServlet() function I am trying to send the user info to my controller which is the OAuthController.java
function SendToServlet(){
$.ajax({
url: "localhost:8080/ui/about",
type: "POST",
data: JSON.stringify({ user:jsonObj}),
contentType: 'application/json',
success: function(result) {
alert(done);
},
error: function(xhRequest, ErrorText, thrownError) {
alert(JSON.stringify(jsonObj));
}
});
}
</script>
My Spring MVC Controller class code has the following implementation - all that it does is that it accepts the user's information and then sets up current user:
#Controller
#RequestMapping("/about")
public class OAuthController {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String post( #RequestBody String items, HttpServletRequest request, HttpServletResponse response)
{
String jsonResp = items;//sb.toString();
ArrayList<String> usercredentials = new ArrayList<String>();
usercredentials = parseJson(jsonResp);
UserMethods usermethods = new UserMethods();
usermethods.setCurrentUser (usercredentials);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
return "{\"success\":\"\"}";
}
public ArrayList<String> parseJson(String json){
}
}
My problem is that the controller is never invoked and actually I never see a Post request to be sent anywhere through Firebug. I've spent several days on it, but still no luck. Do you have any suggestions?
You need to bind value with your function. Your url localhost:8080/ui/about/post is just used to locate the controller but it will not execute any function because you didn't make a call to any function.
To call the function, you have to do like this :
#RequestMapping(method = RequestMethod.POST, value ="/anyValue")
public String anyFunctionName(anyParam){...}
Above function will bind to url localhost:8080/ui/about/anyValue.
Don't you need to call it like this?
url: "localhost:8080/ui/about/post",
but first do this:
#RequestMapping(method = RequestMethod.POST, value = "/post")
How about try to add .html?Application won't add it automatically.
script Array of int and I wish to pass into Spring Controller. but I keep getting
400 bad request.
if my js array is
array = [1,2,3,4]
array -> 400 bad request
JSON.Stringify(array) -> I will get [1,2,3,4]
$.ajax({//jquery ajax
data:{"images": array},
dataType:'json',
type:"post",
url:"hellomotto"
....
})
when I loop the string List.. the first element will be '[1'
#RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(#RequestParam("images") List<String> images){
sysout(images); -> I will get [1,2,3,4]
}
public void
May I know how can I do this properly? I have tried different combination
The following is a working example:
Javascript:
$('#btn_confirm').click(function (e) {
e.preventDefault(); // do not submit the form
// prepare the array
var data = table.rows('.selected').data();
var ids = [];
for(var i = 0; i < data.length; i++) {
ids.push(Number(data[i][0]));
}
$.ajax({
type: "POST",
url: "?confirm",
data: JSON.stringify(ids),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
Controller:
#RequestMapping(params = "confirm", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody int confirm(#RequestBody Long[] ids) {
// code to handle request
return ids.length;
}
#RequestParam is used to bind request parameters, so if you do something like
#RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(#RequestParam("image") String image){
...
}
and you do post to /hellomotto?image=test, the image variable in hellomotto method will contain "test"
What you want to do is to parse Request body , so you should you should use #RequestBody annotation :
http://docs.spring.io/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody
it is using jackson labrary (so you will have to include it as your dependency) to parse json object into java object.
I think you wantAjax call,through ajax, you are sending List of Integers
so in spring your controller will be
#RequestMapping(value = "/hellomotto", method = Request.POST)
#ResponseBody
public void hellomotto(#RequestParam("images") List<Integer> images){
sysout(images); -> I will get [1,2,3,4]
}
*#ResponseBody is missing in Your Code