Spring MVC Ajax POST - java

I'm trying to post a JSON Object, with Ajax, to an Rest Spring MVC Controller, but I met some troubles.
Let's present you my code:
Controller
#RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody JsonResponse checkUsername(#RequestBody JsonUsername username) {
String usernameString = username.getUsername();
JsonResponse response = new JsonResponse();
response.setMessage(usernameString + "Available");
return response;
}
Ajax Function
function displayUsernamError(data) {
var json = "<h4>Eroare</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#usernameError').html(json);
}
function checkUsername(){
var username = document.getElementById("username");
var search = {
"username" : username.value
}
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "http://localhost:8080/skill-assessment/register/checkUsername.html",
data : JSON.stringify(search),
success : function(result) {
console.log("SUCCESS: ", data);
displayUsernamError(result);
},
error: function(e){
console.log("ERROR: ", e);
displayUsernamError(e);
},
done : function(e) {
console.log("DONE");
}
});
}
And finally the html form:
<form:form modelAttribute="user" method="POST" enctype="utf8">
<tr>
<td><label>Username</label></td>
<td><form:input path="name" id="username" /></td>
<td>
<p id="usernameError">
</p>
</td>
</tr>
<button type="button" onClick="checkUsername()">Register</button>
</form:form>
So, I'm calling the checkUsername method when I press click on the Register button, only for test.
The ajax function is called and this send the JSON to the controller. I used the debug and the controller seems to get the JSON Object.
The problem is with the controller Response, because in the error div from my html page, I get this error:
HTTP Status 406
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request \"accept\" headers.
Where is the problem? Who can give me an idea?

You need to specify the below code inside of the request mapping annotation
#RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
you no need to specify the produces attribute because #Responsebody will produce the content based on the request object content type[optional]. if you want other then it then only you have to mention it.
; charset=utf-8 is the default one in Ajax call. you no need mention it separately. try do these changes.

use #ResponseBody need object to json,
seems missing some jar file
(jackson-mapper-asl.jar and jackson-core-asl.jar)
try to import it

First check if your controller is returning a JSON. You can use any REST client and see what is the return header. If not then add the Jackson mapper bean.
Also, try setting the Accept header in the ajax call.
$.ajax({
headers: {
Accept : "application/json",
Content-Type: "application/json"
},
data: "data",
...
})

in .js(java script)
ajax function
var variable="test";
$.ajax({
url: baseUrl + "nameController/test1",
async: false,
data: {val: variable},
dataType: 'html',
success: function (dat) {
console.log(dat);
}
});
you create nameController.java
controller
#RequestMapping(value = "test1", method = RequestMethod.POST)
public #ResponseBody
String checkRoomStatusReservation(#RequestParam(value = "val", required = true) String parse) {
System.out.println("parse"+parse);
//value from parse=test
return parse;
}
you can try this

Related

JAVA: Upload Multipart file

I am struggling with Multipart file upload in Spring controller. I've read multiple questions, googles, but nothing seems to work.
I get
error: "Bad Request"
exception: "org.springframework.web.multipart.support.MissingServletRequestPartException"
message: "Required request part 'file' is not present"
My BE controller:
#RequestMapping(value = "/zip", method = RequestMethod.POST)
public void readFile(#RequestParam("file") MultipartFile file) throws IOException {
// code
}
FE, angularJS:
service.getZip = function getZip(file) {
var formData = new FormData();
formData.append('file', file);
return $http({
method: 'POST',
url: CONSTANTS.readFile,
data: formData,
headers: {'Content-Type': undefined}
}) .then(function (response) {
var data = response.data;
return data.id;
});
}
HTML:
<input type="file" id="file" name="file" accept=".txt"/>
also application.properties contain:
spring.http.multipart.enabled=false
UPDATE:
I no longer get that error when following #Byeon0gam advice to remove #RequestParam from my controller, but the my file is null as it comes to controller. Although in FE service, as I see, it's not empty:
change the Content-Type in your FE to:
headers: {'Content-Type': 'x-www-form-urlencoded'}
hope it will work for you.

How to manipulate jQuery AJAX JSON data in a controller in spring MVC

How many ways are to pass JSON data to a spring controller?
I followed this tutorial and they pass the data using the following syntax:
data: "{\"name\":\"hmkcode\",\"id\":2}",
This works but since I need to retrieve the data from a user using a text input I don't know how to put my variable in that string.
I tried doing using the following syntax:
data: "{\"name\":\name\}"
But it returns the following error:
status: parsererror er:SyntaxError: Unexpected tokken a
I have seen other sites that uses the following syntax:
data: {"name":name}
But that gives me the same error.
This works but I don't know if is the best approach.
var json = {"name" : name};
...
data: JSON.stringify(json),
I manage to pass the JSON string to one of my controllers but I get the string like this:
{"name": Joe, "lastname": Smith}
Is there a way to only get that info in a Person Object or at least get only Joe in a string and Smith in another one?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
function doAjaxPost()
{
// get the form values
var name = $('#name').val();
var lastname = $('#lastname').val();
var json = {"name" : name, "lastname" : lastname};
//console.log(json);
$.ajax(
{
type: "POST",
url: "formShow",
data: JSON.stringify(json),
//data: "{\"name\":name}",
//data: {"name":name},
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
//console.log(data);
console.log(data.name);
//var data = $.parseJSON(JSON.stringify(response));
//alert(data);
alert( "name: "+data.name);
//$('#name').val('');
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}*/
});
}
</script>
<fieldset>
<legend>Name in view</legend>
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastname" name="lastname">
<br>
Show modify name in view: <input type="text" id="modifyname" name=""modifyname"">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</fieldset>
<br>
And these are my controllers:
#RequestMapping(value = "formShow", method = RequestMethod.GET)
public String formularioIncidencia (Model model) {
return "formShow";
}
#RequestMapping(value = "formShow", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody String name)
{
String variableAjax= name;
System.out.println("controller variable is " + variableAjax);
//that prints me this "{name: Joe, lastname: Smith}"
return variableAjax;
}
EDITED****
this is my User class
public class Userimplements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String lastname;
public User(){}
}
I edited my controllers to the following
#RequestMapping(value = "formShow", method = RequestMethod.GET)
public String formShow(Model model) {
return "formShow";
}
#RequestMapping(value = "formShow", method = RequestMethod.POST)
public #ResponseBody User getTags(#RequestBody final User user, Model model)
{
//what should i do here parse my user to JSON how??
user.setName("name changed");
model.("modifyname", user.getName() );
return User;
}
From Ajax you can also pass data as data:'name='+ name+'&lastname='+ lastname,
And at controller end you can make use of #RequestParam annotation to get this value passed from ajax call.
Ajax code looks as follows:
$.ajax({
type: 'POST',
url:'your controller url',
data:'name='+ name+'&lastname='+ lastname,
success: function(msg){
alert('wow' + msg);
}
});
Controller code:
#RequestMapping(value = "formShow", method = RequestMethod.POST)
public String getTags(#RequestParam("name") String name, RequestParam("lastname") String lastname)
{
System.out.println("name: " + name+ " lastname: "+lastname);
String fullName = name + lastname;
return fullName;
}
Hope this helped you.
Cheers:)
For sending the input data to controller, you don't have to necessarily use json as a format. You can simply pass them as request param and extract it on controller using #RequestParam annotation. If you want to post json data you can use JSON.stringify(json). if you to bind object to your model object, try using #Modelattribute on controller and pass the data in your ajax post. There are plenty of examples for this.
Use #RequestParam or #RequestBody to get your data on your controller based on what approach you choose based on point 1.
Use #ResponseBody to send the data back and if you send json data back, use Json.parseJson to convert to js object or if you send a Map, you would get a JS object back in your ajax handler. You can use Dot notation to populate the data.
A few observations will be enlighten ( i hope ).
In JAVA: it is always better to specify your "request" object and your response object like this:
#RequestMapping(method = RequestMethod.POST, value = "/rest/path/to/action",
consumes = "application/json", produces = "application/json")
#ResponseStatus(value = HttpStatus.OK)
public #ResponseBody
List<?> action(#RequestBody List<?> requestParam) {
List<String> myret = new ArrayList<String>();
for (int i=0; i < requestParam.size() ;i++){
myret.add(requestParam.get(i).toString());
}
}
In this case i defined the same object "List" as my request and my response object, but that it's up to your definitions. If you want to represent a user object, you must define your user object and specify the fields u want with Jackson lib. It is a little tricky, but once you got it, you can pass any object you want.
And then you can just pass your data in AJAX as defined in your controller. So in this case would be:
var postData = ["Somedata", "Someotherdata"];
$.ajax(
{
type: "POST",
url: "/rest/path/to/action",
data: postData, // i can do this, because it is defined this way in my controller
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
//etc etc
I hope it helps :)
Cheers

Handling JsonResponse in clientSide view technology of SpringMVC

I am trying to implement the below scenario in Spring MVC.But I am facing issues and not able to decide about the right Approach.
I am Using jsonRequest/jsonResone(Restful Webservices)
1.I have a SignUP.jsp Form which contains few field which need to be submitted to controller.
<form method="POST" onsubmit="javascript:signupObj.signup()">
<table>
<tr>
<td>Username : </td>
<td><input id="username"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input id="password"/></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
2.onSubmit of form it will invoke signup javascript function mentioned below
var signupObj = {
showSignup : function() {
//There are Two Ways to Declare Function The Other Way is function showSignup().Checkout the reasons
$.ajax({
type: "GET",
url: "showSignup",
success: function(response) {
$("#signupView").html( response );
}
});
},
signup : function() {
alert("In Signup function");
var input = '{';
input += '"username":"'+$('#username').val()+'",';
input += '"password":"'+$('#password').val()+'"';
input += '}';
alert(input);
$.ajax({
type: "POST",
url : "signup",
contentType: "application/json; charset=utf-8",
data: input,
dataFilter: function (response) {
return response;
},
// crossDomain: true,
async:false,
success: (function(data) {
alert("In ajax Sucess");
alert(data.profileID);
signupObj.redirectview("success",data);
}),
error : function(data,textStatus,error){
alert("In ajax Failure");
alert(error);
signupObj.redirectview("failure",data);
},
dataType: "json"
});
alert("ajax finished");
},
redirectview : function(message,data) {
alert("inside redirect view");
if(message == "success"){
url = "success";
}
else{
url = "error";
}
$.ajax({
type: "POST",
url : "success",
contentType: "application/json; charset=utf-8",
data: data,
async:false,
dataType: "json",
dataFilter: function (response) {
return response;
},
// crossDomain: true,
success: (function(data) {
alert("data");
}),
error : function(data,textStatus,error){
alert("In ajax Failure redirect");
alert(error);
},
});
}
};
3.The Above javascript function does the ajax call to the controller(input is jsonRequest)
#RequestMapping(value="/signup",method=RequestMethod.POST)
#ResponseBody
public ProfileDTO signup(#RequestBody LoginDTO loginDTO) {
ProfileDTO profileDto = new ProfileDTO();
//In case no errors in backend logic
profileDto.setError(null);
profileDto.setProfileID("profileID");
profileDto.setProfileName("profileName");
System.out.println("Submitting SignUP Form Will Return ProfileID");
return profileDto;
}
//Below method is for success view
#RequestMapping(value="/success",method=RequestMethod.POST)
#ResponseBody
public String checkSignup(#RequestBody ProfileDTO profileDto,HttpServletRequest httprequest,HttpServletResponse httpResponse
) {
//model.addAttribute(loginDTO);
System.out.println("In loginSuccess");
return "loginSucess";
}
4.The Controller gives the JSON Response of profileDTO. Now based on the profileDTO.getErrors I have to call either loginSuccess.jsp or loginFailure.jsp
Now My Question is:
1) How I can use jsonResponse in ajax call to redirect to loginSuccess.jsp or loginFailure.jsp and how will pass my profileDTO data to the loginSuccess view.
2.)Please Suggest me the Best Practice Which should be Followed.
1.) First of all you can reduce your code in javascript like below, Directly serialize the form object.
var signupObj = {
signup : function() {
alert("In Signup function");
$.ajax({
type: "POST",
url : "signup",
data: $('#myForm').serialize(),// add "myForm" as the form id
async:false,
success: (function(data) {
alert("data"+data);
redirectView("success",data);
})
error : function(data, textStatus, errorThrown) {
alert(error_occured);
redirectView("error",data);
}
});
}
};
<script
function redirectView(message,data){
var url = "";
if(message == "success"){
url = "/success";
}else{
url = "/error";
}
$.ajax({
type: "POST",
url : url,
data: data
async:false,
success: (function(data) {
alert("data"+data);
})
error : function(data, textStatus, errorThrown) {
alert(error_occured);
}
});
}
</script>
2.) Redirect the success or failure view from the controller itself.
3.) Pass my profileDTO data to the loginSuccess view.
Spring MVC, from version 3, allows you to return objects directly converted into JSON using the #ResponseBody annotation in a Controller as shown here
#RequestMapping(value="/signup",method=RequestMethod.POST)
#ResponseBody
public ProfileDTO signup(#ModelAttribute("LoginDTO") LoginDTO loginDTO,BindingResult bindingResult) {
ProfileDTO profileDto = new ProfileDTO();
//In case no errors in backend logic
profileDto.setError(null);
profileDto.setProfileID("profileID");
profileDto.setProfileName("profileName");
System.out.println("Submitting SignUP Form Will Return ProfileID");
return profileDto;
}
If Forward from controller
With a prefix of forward, Spring will get a RequestDispatcher for the specified path and forward to it. Part of that process will include taking the Model from the ModelAndView created for that request handling cycle and putting all its attributes into the HttpServletRequest attributes.
The Servlet container will take the RequestDispatcher#forward(..) and again use your DispatcherServlet to handle it. Your DispatcherServlet will create a new ModelAndView with a new Model for this handling cycle. Therefore this Model doesn't contain any of the attributes from before but the HttpServletRequest attributes do.
In your case, this
modelMap.put("key", "value");
will end up being in
HttpServletRequest request = ...;
request.getAttribute("key");

can not able to call spring controller using ajax

I am trying to call a spring controller using ajax, but can not able to go to the controller. I am getting Error 405 Request method 'POST' not supported error. I am keeping my code here please give suggestion to come over it
this is my ajax code calling controller from jsp page, here i am getting the anchor attribute value.
basic.jsp
function organizationData(anchor) {
var value = anchor.getAttribute('value');
$.ajax({
url : "manageOrganization",
method : "GET",
dataType: "json",
contentType: 'application/json',
data: {organizationId : value },
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
controller
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}
here i should get the string to the jsp as a ajax response, but i am getting the error message. Any body can help me.
Regards Sree
For json response you need to add #ResponseBody annotation to your controller method.
You need to use type:"GET" not method:"GET" try it like,
$.ajax({
url : "manageOrganization",
type : "GET", // its type not method
dataType: "json",
.....
Read jQuery.ajax()
Also check that you are returning a json or not.
Your controller is returning String which may be resolved into some other jsp file IF you have configured viewResolver in spring configuration file. Try adding #ResponseBody like this:
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public #ResponseBody
String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}

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