java spring rest parameter not work - java

I created code where pass data to spring rest but don't work correctly see my code below:
#PutMapping("/notification/save/{id}")
public #ResponseBody String update(#PathVariable("id") long id, #RequestBody AccountNotification accountNotification){
String result="ok";
ServiceAccount serviceAccount = new ServiceAccount();
serviceAccount.setId(id);
//accountNotification.setServiceAccount( serviceAccount );
//result =notificationsService.update(id,accountNotification);
JSONObject jObject = new JSONObject();
try
{
JSONArray jArray = new JSONArray();
JSONObject accountNotificationJSON = new JSONObject();
if(result.equals("ok")) {
accountNotificationJSON.put("success", "true");
accountNotificationJSON.put("messages", "Successfully Saved");
}
else {
accountNotificationJSON.put("success", "false");
accountNotificationJSON.put("messages", "NOT Successfully Saved");
}
jArray.put(accountNotificationJSON);
jObject.put("data", jArray);
} catch (JSONException jse) {
logger.error( jse.getMessage());
}
return jObject.toString();
}
my javascrit has:
$("#saveChanges").on('click',function(){
var params1={
proxy:$(proxy).val() ,
port:$(port).val(),
uri:$(uri).val(),
actived:$(actived).val()=="on"?true:false
};
$.ajax({
url: 'notification/save/'+id,
params: params1,
type: 'post',
success:function(response) {
if(response.data[0].success == "true") {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.data[0].messages+
'</div>');
// close the modal
$("#editMember").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.data[0].messages+
'</div>');
}
},
error: function(x, e) {
alert(x);
}
});
in this situation ajax code return 400. Any body knows why? thanks if withdraw #RequestBody annotation the rest has been called but the parameter accountNotifications is initialized but without valeus passed.

there is a put mapping #PutMapping("/notification/save/{id}") in your Rest code, but in your js called by post method type: 'post', so it returns 400 Bad Request, you should use type: put which is equals to your Rest method.
#PutMapping("/notification/save/{id}")
public #ResponseBody String update(#PathVariable("id") long id,
#RequestParam AccountNotification accountNotification){
.....
}
$.ajax({
url: 'notification/save/'+id,
params: params1,
type: 'put',
success:function(){
}})

I resolved this mode:
#RequestMapping(value={"/notification/save/{id}"}, method = {RequestMethod.GET, RequestMethod.POST},
produces = "application/json"
)
public #ResponseBody String update(#PathVariable("id") long id, AccountNotification accountNotification){
String result="ok";
JavaScript:
$("#saveChanges").on('click',function(){
var params1={
proxy:$(proxy).val() ,
port:$(port).val(),
uri:$(uri).val(),
actived:$(actived).is(':checked')
};
$.ajax({
url: 'notification/save/'+id,
data: params1,
type: 'post',
success:function(response) {
I replaced into js param with data

Related

POST request returns 415 error

I'm trying to call a POST request (using Jersey APi for REST) from an HTML form using AngularJS v 1.5.8.
I have an HTML form with a submit button that calls a REST serivce:
<body ng-app="myApp" ng-controller="loginController">
......
<form name="myForm" nonvalidate ng-submit="login()">
......
<div
class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-3 col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-default" ng-submit="login()">Submit</button>
</div>
</form>
This is my loginController script:
var app = angular.module ("myApp", []);
app.controller("loginController", function($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.login = function() {
var transform = function(data) {
return $.param(data);
}
$http(
{
url : 'http://localhost:8080/RestServices/services/user/add',
method : 'POST',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
},
transformRequest : function(data) {
return $.param(data);
},
data: { name: $scope.username,
password: $scope.password }
}).success(function(response, status) {
$scope.data = response; //Assign data received to $scope.data
}
)
}
}
)
And here is my simple REST post service:
#Path("user")
public class UserResource {
private TreeMap<Integer, User> userMap = new TreeMap<Integer, User>();
#POST
#Path("add")
#Consumes({MediaType.APPLICATION_JSON})
public Response addUser(User user) {
int id = userMap.size();
user.setId(id);
userMap.put(id, user);
ObjectMapper mapper = new ObjectMapper();
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
jsonString = null;
}
return Response.ok().entity(jsonString).build();
}
}
The POST request is called but returns a 415 error: the server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
The problem is with the format that the REST API is expecting i.e. JSON.
So try with application/json and specifying charset won't be required:
headers: {
'Content-Type' : 'application/json'
}
function loginController($scope, $http) {
$scope.username = "";
$scope.password = "";
$scope.login = function () {
$http({
method: 'POST',
url: 'user/add',
data: {
username: $scope.username,
password: $scope.password
}
}).success(function (data, status, headers, config) {
$scope.result =data.username;
alert($scope.result);
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}

Spring MVC Ajax POST

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

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

Simple ajax post call in Play framework

Hi I'm trying to simply send a string once a button is pressed in my website using ajax to my java code in Play framework. I can't find a simple tutorial which simply explains how to do this. They are all using templates.
Lets say my java method is:
public static Result upload() { }
and my button is calling a javascript method which gets a String from another input when clicked:
<input id="submit" type="submit" onclick="send();">
I didn't test, but something like this should work.
Application controller
public static Result upload() {
JsonNode node = request().body().asJson().get("stringField");
String inputString = node.getTextValue();"
System.out.println(inputString) // prints the string from the form field
return ok();
}
Routes
POST /uploadfoostring controllers.Application.upload()
Template
<input type="text" id="string-field">
<input id="submit" type="submit" onclick="send();">
<script type = "text/javascript" >
$('#submit').click(function(evt) {
var inputString = $('#string-field').val();
var obj = {
stringField: inputString;
};
$.ajax({
url: "#routes.Application.upload()",
data: JSON.stringify(obj),
headers: {
'Content-Type': 'application/json'
},
type: 'POST',
success: function(res) {
if (res) {
console.log("Success!");
} else {
console.log("Failed...");
}
}
});
}
</script>
POST /home/testPost controllers.Application.testPost
//Server Side.
def testPost = Action { request =>
println("testPost Called");
println(request.body.asFormUrlEncoded.get("name").head);
Ok("Succeeded");
}
Client Side:
public static testPost(){
$.ajax({
url:"/dialog/testPost",
type:"POST",
data:{
name:"Varadharajan R"
},
success:function(response){
alert(response);
}
});
}

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");

Categories

Resources