How to pass json string from jsp page to Spring mvc controller? - java

I need to pass a json string from my jsp page to spring mvc controller.My JSON String and its passing using ajax call is shown below
var datejson = '{'
+'"startmonth" : smonth,'
+'"startday" : sday,'
+'"endmonth" : emonth,'
+'"endday" : eday'
+'}';
alert("json created");
//var jsonfile={json:JSON.stringify(datejson)};
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
dataType: 'json',
url: "/pms/season/json/",
data: JSON.stringify(datejson),
success: function(data) {
alert(data.startmonth + " " + data.endmonth);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
Every time my error function alerts.So how to pass it?
The code to recieve json in Controller class is shown below
#RequestMapping(value = "json", method = RequestMethod.POST)
public void validationDate( #RequestParam ("json") String datejson)
{
//System.out.println("JSON TEST");
System.out.println("JSON CONTENTS ARE::::::"+ datejson );
}
I am new to jquery.Any help will be highly appreciable...

Related

Spring MVC Ajax call POST not working

I have a form which I convert into an object. I wanna pass that object onto the server, a GET ajax request works fine but the object is empty in the java method, then I do the very same request but a POST request and it says error 404. Not sure what I'm doing wrong or what is, followed many examples, but neither of them seem to work.
GET REQUEST
(Ajax call)
$.ajax({
type: "GET",
url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
contentType: 'application/json',
dataType: 'json',
data: { medicalHistoryDTO : medicalHistoryDTO },
success: function(data) {
console.log(data);
}
});
(Object medicalHistoryDTO)
(Java Method)
#RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.GET)
public #ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
System.out.println(medicalHistoryDTO);
return "WORKING FINE";
}
(Eclipse console)
COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE
MedicalHistoryDTO [list=null, medicalHistorySignature=null]
(Browser console)
POST REQUEST
(Ajax call)
$.ajax({
type: "POST",
url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
contentType: 'application/json',
dataType: 'json',
data: { medicalHistoryDTO : medicalHistoryDTO },
success: function(data) {
console.log(data);
}
});
(Java Method)
#RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.POST)
public #ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
System.out.println(medicalHistoryDTO);
return "WORKING FINE";
}
(Browser console)
Keep using POST and to recieve you need to use #RequestBody tag
public #ResponseBody String postEditMedical(#RequestBody MedicalHistoryDTO medicalHistoryDTO)
You can see a working example from my code to https://github.com/shakeelabbas1/webservice/blob/master/src/main/java/com/service/controller/ServiceRequestController.java
Update:
I also see data: { medicalHistoryDTO : medicalHistoryDTO }
Replace it with data: medicalHistoryDTO
try to specify path more strictly
#RequestMapping(value="/{id}/saveMedicalQuestionnair", , method = RequestMethod.POST)
public #ResponseBody
String postEditMedical(MedicalHistoryDTO medicalHistoryDTO, #PathVariable("id") int id)

ajax with spring mvc always getting error

Every request ajax getting an error.
Ajax function:
function doAjax() {
var inputText = $("#info").val();
$.ajax({
type: 'POST',
url: 'ajax',
// data: ({text: inputText}),
dataType: 'json',
data: 'text='+inputText,
success: function (response) {
$("#result_info").text(response);
}
error: function (e) {
alert('error' + e.responseText);
}
});
}
Java Controller
#RequestMapping(value = {"/ajax"}, method = RequestMethod.POST)
public #ResponseBody String showText(#RequestParam String text) {
System.out.println(text);
String returnText = "empty";
if (!text.isEmpty()) {
returnText = " response: " + text;
}
return returnText;
}
Besides this question could you tell what is the difference between in ajax query
data: ({text: inputText}),
data: 'text='+inputText,
In this particular case it's better to change dataType to html instead of json. I solved it.

Need to get the response and to have change in ajax jquery GUI

I have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)

how to post json in request in a struts2 junit4 testcase

The test looks like this :
#Test
public void testSave() throws Exception {
request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
request.setContentType("application/json");
// request.setMethod("post");
ActionProxy proxy = getActionProxy("/save");
actions.MyAction myAct = (actions.MyAction) proxy.getAction();
String result = proxy.execute();
System.out.println("test id : " + myAct.getId());
System.out.println("test name : " + myAct.getName());
assertEquals("success", result);
System.out.println(response.getContentAsString());
}
I'm trying to post a JSON to a struts2 action and I'm getting :
test id : null
test name : null
Although, if I try the same using a JSP :
test.jsp
<script>
var data = '{"id":"1","name":"nitin"}';
$.ajax({
url: "http://localhost:8084/Struts2Junit4/save",
data: data, //returns all cells' data
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function(res) {
console.log(res);
}
});
</script>
I get both the parameters.
I think I'm missing something in writing the test-case. Please help.
The JSONInterceptor looks for the content-type header that is why you need to use request.addHeader instead of request.setContentType.
request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
request.addHeader("Content-Type", "application/json");

Ajax json POST and Spring MVC Controller

I have ajax json POST method like this
$.ajax({
type: 'POST',
url: "localhost:8080/webeditor/spring/json/",
data: JSON.stringify(contents),
dataType: "json"
});
Controller to handle post request
JSONPObject json;
BindingResult result = new BeanPropertyBindingResult( json , "MyPresentation" );
#RequestMapping(value="json/", method = RequestMethod.POST)
public void savePresentationInJSON(Presentations presentation,BindingResult result) {
//do some action
}
but I getting this error
XMLHttpRequest cannot load localhost:8080/webeditor/spring/json/. Cross origin requests are only supported for HTTP.
I'm not sure how to correct above error.
My final work version
var jsonfile={json:JSON.stringify(contents)};
$.ajax({
type: 'POST',
url: "/webeditor/spring/json/",
data: jsonfile,
dataType: "json"
});
AJAX, and
#RequestMapping(value = "/json/", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json)
{
System.out.println( json );
}
Passing JSON with Spring is fairly straight forward. Consider the following jQuery function:
function processUrlData(data, callback) {
$.ajax({
type: "GET",
url: "getCannedMessageAsJson.html",
data: data,
dataType: "json",
success: function(responseData, textStatus) {
processResponse(responseData, callback);
},
error : function(responseData) {
consoleDebug(" in ajax, error: " + responseData.responseText);
}
});
}
Now use the following String #Controller method...
#RequestMapping(value = "/getCannedMessageAsJson.html", method = RequestMethod.POST)
public ResponseEntity<String> getCannedMessageAsJson(String network, String status, Model model) {
int messageId = service.getIpoeCannedMessageId(network, status);
String message = service.getIpoeCannedMessage(network, status);
message = message.replaceAll("\"", """);
message = message.replaceAll("\n", "");
String json = "{\"messageId\": \"" + messageId
+ "\", \"message\": \"" + message + "\"}";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
In my case the request is so simple that I'm just hardwiring the json formatting in the controller method, but you could just as easily use a library like Jackson to produce the json string.
Also as others have stated, verify that the "value" in the #RequestMapping is a unique, legitimate filename. With the json method I show above you don't have to have a corresponding jsp page (in fact it won't use one).
In the URL : url: "localhost:8080/webeditor/spring/json/"
webeditor must be war name or service name so in ur #RequestMapping(value="/webeditor/spring/json/" i think u should not have 'webeditor' it must be only /spring/json
normally 404 means the for the URL requst is wrong or no such service is running for that URL
Looks like jQuery so why not try
$.getJSON('webeditor/spring/json', JSON.stringify(contents, function(data) {//do callbackstuff});
If you wanted to request cross domain the way to do it is like :-
cbFn = function(data) {
// do callback stuff.
}
var ca = document.createElement('script');
ca.type = 'text/javascript';
ca.async = true;
ca.src = server + '/webeditor/spring/json.jsonp?callback=cbFn';
var s = document.getElementsByTagName('head')[0];
s.parentNode.insertBefore(ca, s);
and also add the servlet mapping
<servlet-mapping>
<servlet-name>yourSevletName</servlet-name>
<url-pattern>*.jsonp</url-pattern>
</servlet-mapping>
Your application should have a context root, which would precede the rest of your URL path. And you should also have a servlet-mapping defined in web.xml which defines which requests get directed to your Spring controllers. So if the context root of your application is "myapp" and your servlet-mapping is going to *.html, then your ajax call would look like this:
$.ajax({
type: 'POST',
url: "/myapp/webeditor/spring/json.html",
data: JSON.stringify(contents),
dataType: "json",
success: function(response) {
// Success Action
}
});
In yr jsp include the tag library like so
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Then create a full url using spring
<c:url var="yourFullUrl" value="/webeditor/spring/json/" />
then create javascript variable based on this so you can use in Ajax
<script>
var yourUrl= '<c:out value="${yourFullUrl}"/>';
</script>
No use the javascriptvariable representing the url :
<script>
$.ajax({
type: 'POST',
url: yourUrl,
data: JSON.stringify(contents),
dataType: "json"
});
</script>

Categories

Resources