How To Call Spring MVC Controller From JQuery Ajax Call - java

i am attempting to call Spring controller method from JQuery ajax call, but its not navigate to corresponding view.
First i am verifying login details by calling authenticateLogin() Spring controller function from ajax call, after successful validate i need to forward the request to corresponding view page, i have tried with below code but its not navigate to another page.
Javascript function:
function authenticatePricingCalcLogin() {
var login = {
userName : $("#username").val(),
password : $("#password").val()
};
$.ajax({type: "POST",
url: CONTEXT_PATH+"authenticateLogin",
data:JSON.stringify(login),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
success: function (response) {
if (response != null) {
if (response.errorMsg != null && response.errorMsg != "") { // Login Error
alert(response.errorMsg);
} else {
// Here i need to call spring controller method and to redirect to another page
// I have tried
$.ajax({type: "GET",
url: CONTEXT_PATH+"navigateMainPage",
data:JSON.stringify(loginDO),
contentType : 'application/json; charset=utf-8',
dataType : 'json'
});
}
}
}
});
}
AuthController.java
#RequestMapping(value = "/authenticateLogin", method = RequestMethod.POST)
public #ResponseBody LoginDO authenticateLogin(#RequestBody Login login){
return authService.authenticateLogin(loginDO);
}
#RequestMapping(value = "/navigateMainPage", method = RequestMethod.GET)
public String navigateMainPage(#ModelAttribute("loginDO") Login login,HttpServletRequest request, Model model) {
try {
// Need to set User Name in session variable
} catch (Exception e) {
}
return "auth/mainPage";
}

Please add / in your path
url: CONTEXT_PATH+"/authenticateLogin",

Hi friend I don't have Comment authority so just answering your question.just comment data part if it is GET Type request and remove it form java side #ModelAttribute("loginDO") Login login, Otherwise just make it POST and check any CSRF token is there or not for safe side.

Related

Ajax call Data not Binding

I am trying to bind my form with modelattribute in controller throught ajax call but i didnt get the values in bean e.g all values of bean are null
I printed the form data in alert() its showing me correct data but in controller its showing me null
This is my ajax call and console.log() print whatever i want but in controller i am not getting my data.
Ajax call ::
function viewBugReport(data) {
var formdata=$("#getAppForm_"+data).serialize();
console.log(formdata);
$.ajax({
url : 'displaybugreport.html',
data :formdata,
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
alert(data);
}
});
}
Controller code ::
#ResponseBody
#RequestMapping(value = "/displaybugreport.html")
public String viewBugReport(#ModelAttribute BugReportBean1 bugreportbean,
HttpSession session) {
String ResultMessage = "something went wrong!!";
String adminId = "X";
System.out.println(bugreportbean);
try {
AdminBean adminBean = (AdminBean) httpSession.getAttribute(SESSION_KEY_ADMIN);
adminId = adminBean.getUserId().trim();
ResultMessage = bugReportService.submitBugReport(bugreportbean);
} catch (Exception e) {
logger.debug("GADG:" + adminId
+ " :: Exception occured :: viewBugReort POST method :: BugReportController class");
e.printStackTrace();
}
return ResultMessage;
}
As I can't see the full controller and you haven't mentioned any HTTP method in your desired endpoint, you can try like this:
#RequestMapping(value = "/displaybugreport.html", method = RequestMethod.POST)

How to redirect to another request mapping of a spring MVC controller from a jsp within a jsp

Situation:
I have a jsp within a jsp. I load another jsp into a div of the outer jsp using .html(). I want to redirect my url into an entirely new url mapping from a controller.
Sample controller:
#RequestMapping(value = { "/main/submit" }, method = RequestMethod.POST)
public String main(ModelMap model) {
System.out.println("In controller");
return "redirect:/anotherJSP";
}
#RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST)
public String anotherJSP(ModelMap model) {
System.out.println("In another");
return "anotherJSP";
}
Jsp within a jsp:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
},
error : function() {
alert("Error.");
}
});
Now, the problem is that the outer jsp stays, and the /anotherJSP url only gets loaded in the innerJSP. I wanted to leave the two jsps and go to the new request mapping URL. Is there anyway I can do it? Thanks a lot in advance!
You can't redirect a POST.
When you return redirect:/anotherJSP, the server sends a redirect instruction back to the web browser, and the browser then sends a new GET request for the given URL.
The GET request will be for the URL given, with any query parameters. This means that and POST payload (data) will be lost.
Change #RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST) to #GetMapping("/anotherJSP") (assuming Spring 4.3 or later).
Since an ajax call is asynchronous the effect of return "redirect:/anotherJSP"; is not affecting the browser window, instead you should use window.location.href in your ajax call like this:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
window.location.href = /anotherJSP;
},
error : function() {
alert("Error.");
}
});

What is the correct way to send a string using AJAX with Spring and Thymeleaf? Status : 400

I am getting error ""Required UsernameSearch parameter 'username' is not present" when sending data using ajax with Spring and Thymeleaf. My script is as shown below
<script>
$(document).ready(function() {
$("#opusername").keyup(function() {
var username = $('#opusername').text();
$.ajax({
type : "POST",
contentType : "application/json",
url : "/create/check-username-availability",
data : {"username" : username},
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
});
});
My controller has this method which should receive the string and return a value to indicate whether the username is available or not.
#RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
#ResponseBody
public String checkUsernameAvailability(#RequestParam("username") UsernameSearch username) {
logger.info("Checking username availability for username = " + username.getUsername());
return "true";
}
This is the object I create which contains the username String. I have done this after following tutorials and answers here but nothing seems to work.
public class UsernameSearch {
String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
This is the error when debugging
error:"Bad Request"
exception:"org.springframework.web.bind.MissingServletRequestParameterException"
message:"Required UsernameSearch parameter 'username' is not present"
path:"/create/check-username-availability"
status:400
timestamp:1489942516434
I also wanted to ask how to consume the result from the spring method. Is it possible to get a boolean value?
Change #RequestParam to #RequestBody. Request param != body of the request.
The 400 HTTP error means that the the request is malformed. In your case, the controller expects that the url will have a "username" parameter. Therefore you can either change the ajax call, to send the username as the request parameter, i.e. by attaching "?username=fooBar" to the url you're perfoming POST request and change the controller method signature to accept #RequestParam("username") String username, or change the annotation on the controller parameter to #RequestBody, which tells the controller that the data will be sent as an object in the body of the request.
function ajax:
var data = {
username: $('#opusername').text()
};
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/create/check-username-availability",
data: JSON.stringify(data), // Note it is important
success: function (result) {
// do whatever you want with data
}
});
and in your java method
#RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
#ResponseBody
public String checkUsernameAvailability(#RequestBody UsernameSearch username) {
logger.info("Checking username availability for username = " + username.getUsername());
return "true";
}
Don't send your data as string!
Do the following:
data : {"username" : username},
I think you are getting caught up with the various levels all labeled as username. As your server is written now, it is expecting a parameter which is identified as username to be of type UsernameSearch which is an object with a single property of username. To be explicit, you are expecting the sent body (which is an object) to have a property of username where the value is an object which also has a property called username. So the server is expecting
{
'username': {
'username': 'search value'
}
}
What you are sending is an object with a property of 'username' but a value of string:
{
'username': 'search value'
}
The answer is to be consistent. If you think your search criteria will become more than the one field, then update your client, if not, then change the server to accept a string rather than an object.
Update:
Also, you have #RequestParam but you should use #RequestBody.

Spring Security CSRF Token not working with AJAX

I have a problem in my spring boot app with the csrf token.
I have a form where I can edit a Person. A Person can have
Let us now imagine that the person has a car and enter this and store it. The next time he wants to delete this car and enter another one. I have created that so that there is a list of all of his cars -- he has the option to remove this from the list. Now I'm starting from these pills and want to send with the corresponding ID to the server a POST. When I try I get a 403 forbidden and I have no idea why.
If I change from POST to GET, then it works.
My JavaScript (taken from this site: http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#the-csrfmetatags-tag)
var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
// using JQuery to send a non-x-www-form-urlencoded request
var headers = {};
headers[csrfHeader] = csrfToken;
$.ajax({
url: "./delete/car",
type: "GET",
headers: headers,
});
$.ajax({
url: "./delete/car",
type: "POST",
headers: headers,
});
My controller methods:
#RequestMapping(value = "/{login}/delete/car", method = RequestMethod.GET)
public ModelAndView delete(#PathVariable("login") final String login) {
System.out.println("Stop");
return new ModelAndView("redirect:" + WebSecurityConfig.URL_PERSONS_OVERVIEW);
}
#RequestMapping(value = "/{login}/delete/car", method = RequestMethod.POST)
public ModelAndView deleteInstEmp(#PathVariable("login") final String login) {
System.out.println("Stop");
return new ModelAndView("redirect:" + WebSecurityConfig.URL_PERSONS_OVERVIEW);
}
Any suggestions?
Thanks in advance.
OK, after strugglin with all that, I get the following result.
I added the fail method to the Ajax construct and get the following message:
"Failed to execute 'setRequestHeader' on 'XMLHttpRequest': '${_csrf.headerName}' is not a valid HTTP header field name."
the official spring site advises that you have to put this: <sec:csrfMetaTags /> or from other sources, this: <meta name="_csrf" th:content="${_csrf.token}"/> in your html file.
After this, you should be able to access these attributes in your JavaScript, but in my case I get undefined and ${_csrf.headerName}.
A last try was to take the value from the hidden value (chapter 24.5: http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#the-csrfmetatags-tag).
Now, I have the following:
$(function () {
var token = $("input[name='_csrf']").val();
var header = "X-CSRF-TOKEN";
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
$.ajax({
url: "./delete/car",
type: "POST",
success:function(response) {
alert(response);
}
});
With this it works like a charm.
Another way, you can use the following code:
$.ajax({
url : './delete/car',
headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
type : 'POST',
success : function(result) {
alert(result.msgDetail);
}
})
I suggest you first check if a valid csrf token and the header have been generated using chrome debugger. If not, then have you added the <sec:csrfMetaTags /> in the <head>?(you will need to import the spring security taglibs). If using Apache tiles, you will have to add this at the <head> section of the template file being used for the view.
If the token is not empty, then in your security-context/configuration file, check if you have disabled csrf security by any chance. By default it is enabled and needs to be for this process to work.

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

Categories

Resources