Put request into Spring Boot Controller - ajax

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.

Related

ajax MissingServletRequestParameterException: Required request parameter is not present]

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 ...

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

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;
}

calling restful service from different server

Hi All i am working on spring3.0 restful webservice.i am able to invoke my method when i am calling the method from the same server(i.e my weblogic server).but if i want to consume\hit the same method from another server(i.e my jboss server) then it is not hitting my rest method which is on weblogic server.
in the below code if this code i am writing in weblogic jsp page and calling it is returnig me correct value and i can display the same on my web page.but if i am copying the same code to jsp in JBOSS server(my different project to access my rest service) then it is not hitting my method.
---------------------------------------
$.ajax({
url: "http://test.abc.org:7001/SpringRestService/restful/products/ALL/ALL/ALL/ALL.json",
type: "GET",
processdata: true,
dataType: "json",
contentType: "application/json;",
beforeSend: function () { },
headers :
{
"Content-Type" : "application/json",
"Accept" : "application/json",
"Access-Control-Allow-Origin":"http://its-ims002.neahq.nearoot.org:7001/"
},
success: function (data)
{
bindEvent.loadGridData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
try
{
alert(JSON.stringify(XMLHttpRequest) + "\n" + textStatus + "\n" + errorThrown);
}
catch (ex) { alert("Exception occured.. "); }
finally { }
}
});
below is my java code which i have kept in my weblogic server and this i have to hit from jboss server using my ajax call.
---------------------------------
#Controller
public class HelloWorldController1 {
#RequestMapping(value = "/products/{userName}/{year}/{status}/{stateId}", method = RequestMethod.GET,consumes="application/text")
public ModelAndView getTextFromURL(#PathVariable("userName") String userName, #PathVariable("year") String year,
#PathVariable("status") String status, #PathVariable("stateId") String stateId) {
List<Abc> list= new ArrayList<Abc>();
list= service.products(userName, year, status, stateId);
ProductList productList = new ProductList (list);
ModelAndView mav = new ModelAndView();
mav.setViewName("index1");
mav.addObject("list", productList );
return mav;
}
}
Even though you have 'Access-Control-Allow-Origin' specified for the other(jboss) server, the browser might not allow this as this breaches the 'same origin policy'
If your service returns json, you can easily do this by making use of script utilities such as "dojo.io.script" as json or javascript is not affected by 'same origin policy'.
If its not json, there might not be any other option other than "dojo.io.iframe" if that suits you. hope this helps ...
EDIT: I see that your service returns JSON, have you tried using dojo.io.script ? or any other similar utilities that your JS framework has.

Resources