Saturday 2 November 2019

Working with Ajax and Spring MVC

Working with Ajax and Spring MVC

Simple example for ajax call or form posting using spring mvc as below.

Validation using Ajax call:

Ajax call:

$.ajax({
url: "your-application-url",
type:"POST",
success: function(result){
if(result!=null){
//do Operation 
}else{
//do else Operation 
}
}
});


Spring mvc :

@ResponseBody
@RequestMapping(value = your-app-url, method = RequestMethod.POST)
protected String validatefunction(@RequestParam String param) {
try {
//Do operation
}
catch (Exception e) {
}
return null;
}

Form Posting using Ajax:

Ajax call:

$.ajax({
type: "POST",
url: "application-post-url",
data: $("#editForm").serialize(),
    success: function(data){
data = JSON.parse(data);
if(data !=null){
//do operation
}
}
});

Spring mvc:

@RequestMapping(value = "app-post-url", method = RequestMethod.POST)
public @ResponseBody String save(@ModelAttribute("user") @Validated 
                User dto, BindingResult result) {
try {
//do operation
         }
    catch (Exception e) {
        }
JSONObject jsonObj = new JSONObject();
jsonObj.put("key", "value");
        return jsonObj.toString();
}


Alert function in JS:

Basic alert with confirmation button:

swal({
title: '<spring:message code="message.main.property"/>',
icon: "warning",
buttons: ["<spring:message code='message.cancel'/>","<spring:message code='message.confirm'/>"],
dangerMode: true,
})
.then(function(isclick) {
  if (isclick) {
  //do operation - call ajax or url redirect
  }
});

Form Post based on on-click:

$(document).on('click', '.btnClassId', function (e) {
$('#editForm').attr('action', '${pageContext.request.contextPath}/app-url');
$('#editForm').submit();
});


Redirection to the specified url:

window.location.href="${pageContext.request.contextPath}/application-url";




No comments:

Post a Comment

Working with Ajax and Spring MVC

Working with Ajax and Spring MVC Simple example for ajax call or form posting using spring mvc as below. Validation using Ajax call...