ajax MissingServletRequestParameterException: Required request parameter is not present] - ajax

I have the error :
MissingServletRequestParameterException: Required request parameter 'employee' for method parameter type Employee is not present]
I don't understand why.
function createEmployee() {
const employee = {};
employee.id = document.getElementById("detailledMatriculeDataLabelId").value;
employee.firstName = document.getElementById("detailledFirstNameDataLabelId").value;
employee.lastName = document.getElementById("detailledLastNameDataLabelId").value;
employee.address = document.getElementById("detailledAddressDataLabelId").value;
employee.title = document.getElementById("detailledTitleDataLabelId").value;
employee.managerId =1;
$.ajax({
url: '/create' ,
data : employee,
type: 'POST ',
success: function(result) {
document.location.reload()
},
error: function() {
console.log ("creation failed ");
}
});
}
'''
#PostMapping(path="/create") // Map ONLY POST Requests
public String createEmployee (#RequestParam Employee employee) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
System.err.println("createEmployee");
employeesRepository .save(employee);
return "/index";
}
'''

I have found many posts, and after many tries got it:
for ajax
data: JSON.stringify(employee),
contentType: "application/json",
and for the java code: replace the #RequestParam with #RequestBody.
AI does not understand why if someone has the answer ...

Related

Put request into Spring Boot Controller

Im trying to send a json string with ajax to my spring boot controller but i keep getting the error net::ERR_TOO_MANY_REDIRECTS, and there are a bunch of $csrfError after the url. I've looked at tons of other websites and questions but I still can't get it to work. how do i correctly setup my ajax request so that my controller will accept the data?
ive already tried changing the method type to post and changing the RequestParams to ResponseBody but i went back to RequestParams
my ajax function
function deleteEvent() {
var startTime = document.getElementById('newStartTime').value;
var endTime = document.getElementById('newEndTime').value;
var type = document.getElementById('newTimeOffType').value;
var search = {startTime: startTime, endTime: endTime, type: type};
if(confirm("Are you sure you want to delete this event?")){
$.ajax({
method: 'PUT',
contentType: 'application/json',
url: '/vacation/deleteEvents',
dataType: 'json',
data: JSON.stringify(search),
success: function () {
console.log('success');
},
error: function (e) {
console.log(e);
}
})
}
else {
alert('you said no')
}
my spring controller
#RequestMapping(value = "/vacation/deleteEvents", method=RequestMethod.PUT)
#ResponseBody
public String deleteCalendarEvents(#RequestParam String startTime, #RequestParam String endTime, #RequestParam String type, HttpSession session ){
User user = (User) session.getAttribute("currentUser");
System.out.println("startTime: " + startTime);
System.out.println("endTime: " + endTime);
System.out.println("type: " + type);
return null;
}
i want it to print out the starttime, endtime, and type into my console but i keep getting this error.

Receiving response as JSON in ajax call in jsp

I have a jsp page that sends response as a json. The page is requested through AJAX call. But the response went into Ajax error part instead of success part.
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers
The following is my jsp page Script:
$("#Student").delegate("select[id='year.id']", "change", function () {
//alert("hi");
var id = $(this).attr('id');
var value=$("select[id='year.id']").val();
//alert(id);
//alert(value);
//console.log($(id).val());
$("select[id='classs.id']").empty();
$("select[id='classs.id']").append('<option value="">Select Class</option>');
$("select[id='section.id']").empty();
$("select[id='section.id']").append('<option value="">Select Section</option>');
$.ajax({
type: 'GET',
url: 'getStandard',
contentType: "application/json;charset=utf-8",
datatype: "Json",
data: { Year: value },
success : function(datas) {
$.each(datas, function (i, data) {
$("select[id='classs.id']").append('<option value="' + data.id + '">' + data.name + '</option>');
});
}
});
return false;
});
This Is my server side code where I am getting the response as Student object :
Controller :
#RequestMapping(value = "/getStudentName", method = RequestMethod.GET)
public #ResponseBody String getStudentName(#RequestParam("Year") String idYear, #RequestParam("Classs") String idClass, #RequestParam("Section") String idSection) throws JsonProcessingException
{
List<Student> student = userService.getStudentName(idYear,idClass,idSection);
return student ;
}
I am new to ajax using via Spring
#RequestParam is a parameter in the uri (http://uri?year=2018). If what you want is JSON then you should use #RequestBody instead

Spring Exception: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported

I have a ResponseEntiy that receives a comment:
#RequestMapping(value="/save-comment", method=RequestMethod.POST)
#ResponseBody
public ResponseEntity<?> saveComment(#RequestParam("name") String comment, #RequestParam("id") long id) {
SiteUser user = authController.getUser();
String cleanedCommentBody = htmlPolicy.sanitize(comment);
StatusUpdate status = statusUpdateService.getOneById(id);
Comment createdcomment = new Comment();
createdcomment.setCommentdate(new Date());
createdcomment.setCommenttext(cleanedCommentBody);
createdcomment.setStatusUpdate(status);
createdcomment.setSiteUser(user);
commentService.createComment(createdcomment);
return new ResponseEntity<>(null, HttpStatus.OK);
}
The code in my JSP works fine.... it sends the values to my Controller method and the method receives it, process the information and saves the new comment in the database, but after that, showing the same page.... it gives me the error. But other POST request I have work fine.
http://192.168.160.128:8080/viewonestatus/58
Exception: org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'POST' not supported
Failed URL: http://192.168.160.128:8080/viewonestatus/58
Exception message: Request method 'POST' not supported
The AJAX snippet is that gives an ok code is:
.....
<c:url var="saveComment" value="/save-comment" />
.....
function saveComment(text) {
//alert("El texto es...text " + text);
editComment(text, "${status.id}", "${saveComment}");
}
function editComment(text, id, actionUrl) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
jqXHR.setRequestHeader(header, token);
});
$.ajax({
'url' : actionUrl,
data : {
'name' : text,
'id' : id
},
type : 'POST',
success : function() {
alert("Ok");
},
error : function() {
alert("error");
}
});
}

How to send Long and Double through Ajax to Spring controller?

I want to send Long and Double to Spring controller use Ajax.
var id = $(this).data('customer-id');
var quantity = $('#quantity-' + id).val();
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
url: '/changeQuantityOrder',
data: {idOrder: id, quantityChange: quantity},
error: function(e) {
console.log(e);
},
success: function (msg) {
window.location.href = "/administrationNotSleeps";
}
I try to receive a code so:
#RequestMapping(value = "/changeQuantityOrder", method = {RequestMethod.POST})
public #ResponseBody Long editCustomerOrder(#RequestParam(value = "idOrder")Long id,
#RequestParam(value = "quantityChange")Double quantity){
System.out.println("Id:"+id+" Quantity "+quantity );
return id;
}
But I receive exception
{"timestamp":1490775639761,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required Long parameter 'idOrder' is not present","path":"/changeQuantityOrder"}"
I looked for and have found about this exception (MissingServletRequestParameterException) https://stackoverflow.com/
But this article was written 3 years ago, maybe something changed?
Because now I send String to Spring controller and after that I use split in java.
key should be in quotes
data: {"idOrder": id, "quantityChange": quantity}
Also mention dataType - what kind of response to expect.

How to pass Json object from ajax to spring mvc controller?

I am working on SpringMVC, I am passing data from ajax to controller but i got null value in my controller please check my code below
function searchText()
{
var sendData = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
url: "/gDirecotry/ajax/searchUserProfiles.htm,
async: true,
data:sendData,
success :function(result)
{
}
}
MyControllerCode
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(HttpServletRequest request)
{
String pName = request.getParameter("pName");
//here I got null value
}
any one help me
Hey enjoy the following code.
Javascript AJAX call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.html",
data: JSON.stringify(search), // Note it is important
success :function(result) {
// do what ever you want with data
}
});
}
Spring controller code
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestBody Search search, HttpServletRequest request) {
String pName = search.getPName();
String lName = search.getLName();
// your logic next
}
Following Search class will be as follows
class Search {
private String pName;
private String lName;
// getter and setters for above variables
}
Advantage of this class is that, in future you can add more variables to this class if needed.
Eg. if you want to implement sort functionality.
Use this method if you dont want to make a class you can directly send JSON without Stringifying. Use Default Content Type.
Just Use #RequestParam instead of #RequestBody.
#RequestParam Name must be same as in json.
Ajax Call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
/*contentType : 'application/json; charset=utf-8',*/ //use Default contentType
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.htm",
data: search, // Note it is important without stringifying
success :function(result) {
// do what ever you want with data
}
});
Spring Controller
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestParam String pName, #RequestParam String lName) {
String pNameParameter = pName;
String lNameParameter = lName;
// your logic next
}
I hope, You need to include the dataType option,
dataType: "JSON"
And you could get the form data in controller as below,
public #ResponseBody String getSearchUserProfiles(#RequestParam("pName") String pName ,HttpServletRequest request)
{
//here I got null value
}
If you can manage to pass your whole json in one query string parameter then you can use rest template on the server side to generate Object from json, but still its not the optimal approach
u take like this
var name=$("name").val();
var email=$("email").val();
var obj = 'name='+name+'&email'+email;
$.ajax({
url:"simple.form",
type:"GET",
data:obj,
contentType:"application/json",
success:function(response){
alert(response);
},
error:function(error){
alert(error);
}
});
spring Controller
#RequestMapping(value = "simple", method = RequestMethod.GET)
public #ResponseBody String emailcheck(#RequestParam("name") String name, #RequestParam("email") String email, HttpSession session) {
String meaaseg = "success";
return meaaseg;
}

Resources