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 ?
Related
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
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
In an ASP.NET MVC project, I have a controller method that accepts POST requests, like so (with the "User" class for completeness):
[HttpPost]
public ActionResult TestMethod(User user)
{
return Content("It worked");
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}
I call this method with jQuery Ajax:
$.ajax({
url: '/test/TestMethod/',
data: JSON.stringify({ user: { name: 'NewUserName', email: 'username#email.com' } }),
type: 'POST',
success: function (data) {
alert(data);
},
error: function (xhr) {
alert('error');
}
});
When I create a fresh ASP.NET MVC project, and include this code in a new Test controller, everything works fine. Viewed through Fiddler, a single POST request is made, and I get the controller method return value back.
However, when I run this code in the current MVC project that I'm developing, it doesn't work. From Fiddler I see that the ajax call first initiates a POST method, that gets a 301 http status error ("moved permanently"?). Immeditely afterwards a GET request is made, which generates a 404 not found error (which makes sense as there is no GET action method with this name available).
So I use the exact same code, in a fresh projects and in the existing project, but the code only works in the fresh project. So clearly there's something about my existing project that somehow prevents this from running properly (and causes the odd behaviour of generating both a POST and a GET request). But I have no idea what it could be, so any suggestions welcome...!
Update - routing information:
public static void RegisterRoutes(RouteCollection routes)
{
routes.AppendTrailingSlash = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
Update 2:
Looks like this issue is caused by Content Security Policy settings that were switched on for this project.
You need to put the [FromBody] annotation before your method's argument.
[HttpPost]
public ActionResult TestMethod([FromBody]User user)
{
return Content("It worked");
}
ASP.net MVC framework will use the arguments you pass in the body to recognize the method.
I ran into this issue after I implemented Custom Errors, and My form was posting a File back to the server tthat was larger than the Max Allowed. This resulted in a 404.13 error... I guess that is the default error for "file too large"
When custom errors were turned on all I saw was the 404. It was driving me crazy that I was getting a 404 error when I knew that the request type was a post, and the url where it was posting was correct.
Hope this helps someone.
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.
I get the following error "Web Service method name is not valid" when i try to call webmethod from javascript
System.InvalidOperationException: SaveBOAT Web Service method name is not valid.
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
HTML Code :
<asp:LinkButton runat="server" ID="lnkAddBoat" OnClientClick="javascript:AddMyBoat(); return false;"></asp:LinkButton>
JS Code :
function AddMyBoat() {
var b = document.getElementById('HdnControlId').value;
jQuery.ajax({
type: "GET",
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/text",
dataType: "text",
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
C# Code (Web method in AllService.asmx file)
[WebMethod]
public static string SaveBOAT(int Pid)
{
// My Code is here
//I can put anythng here
SessionManager.MemberID = Pid;
return "";
}
I tried all solutions found on Stack Overflow and ASP.NET site.but none of them worked for me.
It was a silly mistake.
remove Static keyword from method declaration.
[WebMethod]
public string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
In my case I had copied another asmx file, but not changed the class property to the name of the new class in the asmx file itself (Right click on asmx file -> View Markup)
In my case the error was that the Web Service method was declared "private" instead of "public"
Try using this, I think datatype should be JSON
jQuery.ajax({
type: "POST", // or GET
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/json; charset=utf-8",
dataType: "json"
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
And in C# Code change Pid to string
[WebMethod]
public static string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
I too faced the similar issue. The solution includes checking everything related to ensuring all name, parameters are passed correctly as many have responded. Make sure that the web method name that we are calling in UI page is spelled correctly, the data, data types are correct and etc. In my case, I misspelled the web method name in my ajax call. It works fine once I found and corrected the name correctly.
For Ex: In .asmx class file, this is the method name "IsLeaseMentorExistWithTheSameName" but when I called from UI this is how I called:
var varURL = <%=Page.ResolveUrl("~/Main/BuildCriteria.asmx") %> + '/IsLeaseMentorExistWithSameName';
Notice that the word "The" is missing. That was a mistake and I corrected and so it worked fine.
As Sundar Rajan states, check the parameters are also correct. My instance of this error was because I had failed to pass any parameters (as a body in a POST request) and the asmx web method was expecting a named parameter, because of this the binding logic failed to match up the request to the method name, even though the name itself is actually correct.
[WebMethod]
public object MyWebMethod(object parameter)
If there is no parameter in the body of the request then you will get this error.
Did U add ServiceReference Class. Check this once. Based on your comment I can tell what to do
I had this issue because my soap method had a List<string> parameter. Couldn't figure out a way to make it work with the array parameter; so just converted the parameter to a &-delimited string (e.g. val1&val2&val3) and converted the parameter to an array in the service method.
In my case, one of the WebService receiving parameters was called aId. When I called it from javascript, I was sending the correct Id value, but the name of the sent variable was incorrectly called bId. So I just had to rename the WebService call, keep the correct value like before, and just change the variable name.