Jquery Ajax POST not working. works fine for GET - javascript

I am trying to post jquery Ajax request but it does not go to my MVC controller.
$.ajax({
url : contextPath + "/check/panelnumber",
type : "POST",
contentType : "application/json",
data :{
"execution" : execution,
"panelNumber" : panelNumber
},
});
Spring MVC controller
#Controller
#RequestMapping("/check")
public class ValidateFieldValueController extends FlowEnabledBaseController {
#RequestMapping(value = "/panelnumber", method = RequestMethod.POST)
public ResponseEntity<String> checkPanelNumber(HttpServletRequest request,
HttpServletResponse response,
#RequestParam("panelNumber") String panelNumber,
#RequestParam("execution") String execution) {
......
Gson gson = new Gson();
return new ResponseEntity<String>(gson.toJson(details), HttpStatus.OK);
}
However it works perfectly fine for GET method!
Tried adding dataType: "json" as well but with this even GET call stops working. Browser console shows error as HTTP 400 bad request but when checked through firefox plugins the POST parameters are going fine.
Any help?

Spring is a little touchy when it comes to #RequestParam, POST body, and JSON content-type: it simply won't parse them. You can solve this problem one of three ways:
Change the content-type to be application/x-www-form-urlencoded
Change the two #RequestParam to be a single #RequestBody Map<String, Object> body, then use that Map to manually parse out your parameters.
Set up a custom Argument Resolver that can parse JSON for your desired values.
The second method is likely the easiest to change, but it loses you some of the automagic validation that Spring does for you.

Related

Javascript AJAX call to SpringBoot controller and getting response in JSON

I am trying to hit my SpringBoot controller with a JSON and for that I am using AJAX. I want my controlelr to receive the AJAX call, extract the JSON, works with the values and return a JSON response back to the script which I will then utilize in some way.
I am not able to figure out how to code my controller so as to handle the AJAX and also if the request should be POST or GET ?
Here is my script code:
<script>
database.on('child_added', function (snapshot) {
var data = {};
data["FirstName"] = snapshot.val().FirstName;
data["LastName"] = snapshot.val().LastName;
data["Number"] = snapshot.val().Number;
$.ajax({
type: "GET",
contentType: "application/json",
url:"my-localhost/application/print",
data: JSON.stringify(data),
dataType: 'json',
cache: false,
success: function(){
console.log("Successfully sent payload")
},
error: function(e){
console.log("Error": , e)
}
});
</script>
Here is my controller for now. I dont know how and what to change in it and how to send the response back to the script:
#RestController
#RequestMapping("/application")
public class AppController
{
#GetMapping("/print")
public void print()
{
System.out.println("Hello World");
}
}
I am not able to figure out how to code my controller so as to handle the AJAX and also if the request should be POST or GET ?
Your service method is annotated as #GetMapping("/print") so it should be GET request. I suggest reading a bit more on various HTTP methods and then decide which one serves you best.
Here is my controller for now. I dont know how and what to change in it and how to send the response back to the script.
You should be returning the object which encapsulates the data you want to send back to the consumer.
Simply it has three steps
Create DTO object (property name must be according to your JSON object names)
User #RequestBody in your method
Use #ReponseBody and simply return the object.
Example:
Consider it you want to send some user information, do some business and return that user to the javascript (UI).
Create DTO class for user
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserDto {
private Long id;
private String name;
private String family;
private String password;
private String username;
private String nationalId;
private String email;
//Getters and Setters
}
Put #RequestBody and User class as the input of the controller
method.
Simply return user object.
#RestController
#RequestMapping("/application")
public class AppController {
//Changed to #PostMapping
#PostMapping("/print")
public User print(#RequestBody User user) {
//Do whatever you want to user
System.out.println("Hello World" + user.getUsername());
return user;
}
}
Some notes
#RequestBody, works as a converter to convert sent JSON to a java class (Convert user JSON to User.class)
#ResponseBody, is inverse of #RequestBody, it converts java classes to JSON (Convert User.class into user JSON)
As you're sending data to the server it's good for you to use POST
instead of GET. GET OF POST
DTO object property names (family, id,...) must be the same as your
JSON property names. Otherwise, you must use #JsonProperty.
Further information about JsonProperty
When you're using #RestController you don't need to use
#ResponseBody
because it's in body of #RestContoller

AJAX POST request in Spring-MVC does not works

I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public JSONArray addUser(#ModelAttribute("UserTest") JSONArray name) {
System.out.println(name.toString());
return name;
}
}
AJAX Request:
<script>
function addUser() {
var json = '{"uname":"John", "Age":42}';
obj = JSON.parse(json);
$.ajax({
url : "/addUser",
data : obj,
type : "POST",
async: false,
contentType: "application/json",
success : function(response) {
alert( response );
},
error : function() {
alert("error...."); //this is being popped-up in my browser
}
});
}
</script>
POST http://localhost:8090/addUser 404 ()
Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser
AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
url : "/<app_name>/addUser"
The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser

JQuery ajax- current URL doesn't work

I've looked at thousands of articles about my problem, but i didn't found a solution.
Here we go.
When I'm using ajax with url specified as the url of view when i want to use a script it doesn't work. I'm using POST type and receiving data in spring controller. When I change url to something else and do the same in requestmapping value, everything works fine. What possibly causing this problem ? AJAX:
$.ajax({
type : "POST",
url : "/login2",
data :
{x: x}
,
success : function() {
alert('fine');
},
error: function(xhr, status, error) {
alert(xhr.status+status+error);
}
});
SPRING:
#Controller
#RequestMapping
public class LoginController {
#RequestMapping(value = "/login",method = RequestMethod.GET)
public String login() {
return "login";
}
#RequestMapping(value = "/login2",method =RequestMethod.POST)
public #ResponseBody void login2(#RequestParam(value="x[]") String x[]){
System.out.println(x[1]);
}
}
Code above works fine but
When url is "/login" for whole class and methods are specified the same it doesn't work ..
Can You help me please ?
Your parameter for login2 is array of string. Whereas you are sending object from ajax.
try reading the values from Request body instead of request param.
login2(#RequestBody String x[])
Maybe problem is that this is my page declared as login apge in Spring Security ?

Passing a javascript variable in Ajax to a Java class

I am passing a javscript variable to a java class. I am not sure if this is consider a proper way, if so is my syntax correct and how can i make sure that the variable has passed successfully to my java class?
var key = record.getKey();
$.ajax({
type: "POST",
url: "apps/APP/src/Test.java",
data: {id : key},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
A simple Java Class cannot handle an Ajax request (or any web request for that matter) You should be having a Java Web application/ Dynamic Web Application, either written with vanilla Servlets and JSP or using any frameworks like spring to handle web requests.This application must be deployed on a Servlet Container like Tomcat or Jetty.
This tutorial should get you started as its too broad to be covered in a SO answer. Do get back with a new question if you face any issues.
Updated as per your comment:
Since you have a Dynamic Web Application It should have a Servlet, and as your Ajax request is using POST method, override the doPost() and get the data from request object. Note: Use POST only if you are mutating some data in the backend else use GET.
Please see the below code.
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
request.getParameter("id"); //use the key of the json data you need
}
}

How can I get a Spring #RestController to accept parameters in JSON format rather than www-form-urlencoded?

Using Spring 4.1.7 on JDK 1.8, I have an #RestController class that looks like this:
#RestController
public class ServiceAController {
public static final Logger LOG = Logger.getLogger(ServiceAController.class);
#RequestMapping(value="/rest/servicea", method=RequestMethod.POST)
public ServiceAResponse serviceA(#RequestParam(value="parmA", defaultValue="defaultParmA") String parmA,
#RequestParam(value="parmB", defaultValue="defaultParmB") String parmB,
#RequestParam(value="parmC", defaultValue="defaulParmC") String parmC) {
LOG.info("Inside Service A handler: " + parmA + " B: "+ parmB + " C: "+ parmC);
}
When I send a POST to /rest/servicea from a javascript like this, everything works, and I see the values "a", "b", and "c" printed in my log:
var data = {
"parmA": "a",
"parmB": "b",
"parmC": "c"
}
$.ajax({
type: "POST",
url: "./rest/servicea",
contentType: "application/x-www-form-urlencoded",
data: data,
dataType: "json",
success: submitAuthSuccess,
error: submitAuthFailure
})
However, when I try to change the call from the javascript to this (to change the protocol to REST rather than www-urlencode), I get the default values (defaultParmA, defaultParmB, defaultParmC) in my log:
var data = {
"parmA": "a",
"parmB": "b",
"parmC": "c"
}
$.ajax({
type: "POST",
url: "./rest/servicea",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: submitAuthSuccess,
error: submitAuthFailure
})
I think I'm missing something in the #RestController class to get it to parse the JSON rather than expecting www-urlencoded data.
I tried changing the #RequestMapping annotation on the serviceA method to add the consumes="application/json" attribute, but that had no effect.
What can I change to make this work, using JSON rather than urlencoded data in the POST body?
The #RequestParam javadoc states
Annotation which indicates that a method parameter should be bound to
a web request parameter.
This is retrieved through the various ServletRequest methods for request parameters. For example, ServletRequest#getParameterMap() which states
Request parameters are extra information sent with the request. For
HTTP servlets, parameters are contained in the query string or posted
form data.
In your second snippet, you aren't sending either. You're sending JSON in the request body.
Spring has a mechanism (it has many, and custom ones) for deserializing that into the data you expect. The standard solution is #RequestBody, assuming you have an appropriately registered HttpMessageConverter that can handle the JSON. Spring automatically registers MappingJackson2HttpMessageConverter if you have Jackson 2 on the classpath, which can correctly deserialize JSON into Java POJO types.
The documentation gives a number of examples and explains how you would use it. With JSON, you could define a POJO type with fields that correspond to the ones you send
class RequestPojo {
private String paramA;
private String paramB;
private String paramC;
// and corresponding getters and setters
}
and add a #RequestBody annotated parameter of this type to your handler method
public ServiceAResponse serviceA(#RequestBody RequestPojo pojo) {
pojo.getParamB(); // do something
return ...;
}
Jackson lets you define, through annotations or through configuration of the ObjectMapper, how to deal with absent values.
#RestController is not involved here. As its javadoc states,
Types that carry this annotation are treated as controllers where
#RequestMapping methods assume #ResponseBody semantics by default.
It looks to me like you are passing a single JSON object at this point, rather than a set of parameters, hence Spring cannot match what you're sending to any of the parameters you've provided.
Try
#RequestBody List<ListUnit> listOfUnits
instead of #RequestParam

Categories