How to pass value from jsp to controller using jquery - java

I want to know how can I pass the parameters from JSP to the controller.
I am trying to send through ajax call but its going to error function
HTML:
<input type="submit" name="syncSubmit" value="synchronize" id="submitSync" >
JSP:
$("#submitSync").click(function() {
var campaignId = [];
var accountSe_Id = $ {
accountSe_Id
};
var accountId = $ {
accountId
};
$("#selectedCampaigns option").each(function() {
campaignId.push({
"campaignId": $(this).val()
});
});
$.ajax({
type: "POST",
url: "/partial-synch.json",
processData: true,
data: {
campaignId: JSON.stringify(campaignId),
accountSe_Id: accountSe_Id,
accountId: accountId
},
dataType: "json",
success: function(data) {
},
error: function(data) {
alert("fail");
}
});
return false;
});
Controller:
#RequestMapping(value = "/partial-synch.json", method = RequestMethod.POST)
#ResponseBody
public Object[] partialSync(
#RequestParam("campaignId") String campaignId,
#RequestParam("accountSe_Id") long accountSe_Id,
#RequestParam("accountId") long accountId) {
Object[] resposneBody = new Object[1];
}

Related

Pass model and a string using ajax to Spring MVC

Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.

How to pass JSON array from AngularJS Controller to the Spring Controller?

I am making SPA using AngularJS in Spring 4 with Hibernate 5.
I'm getting an error while passing JSON array from the AngularJS controller to the Spring Controller.
All fields value successfully coming in angular JSON array, but not passing in Spring controller.
Error: Could not read JSON: ; nested exception is
com.google.gson.JsonSyntaxException:
My project structure is like below.
Spring_Hibernate_MVC
=src
-com->karmesh->mvcApp->controller->register->RegisterController.java
=WebContent
-js->app->RegisterController.js
-Views->Register.html
Register,html
<div id="DivRegisterMain" ng-controller="RegisterController">
<form name="myForm" novalidate>
:::://Form fields here.
<input type="submit" value="SubmitTest" ng-click="submit()" ><br>
</form>
</div>
app.js
var routeApp=angular.module("RouteApp",['ngRoute']);
RegisterController.js
routeApp.controller("RegisterController", function($scope, $http) {
$scope.regJson = {
"is" : 1,
"fname" : "",
"lname" : "",
"gender" : "",
"dob" : "",
"email" : "",
"contact" : "",
"yop" : "",
"degree" : "",
"branch" : "",
"perc" : "",
"state" : "",
"city" : ""
};
$scope.studentList = [];
$scope.submit = function() {
var req = {
method: 'POST',
url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: $scope.studentList,
};
$http(req).
then(function(response){
console.log(response); // prints true or false
if (response)
console.log("in success");
else
console.log("in fail");
$scope.studentList=[];
}, function(response){
console.log(response.status);
console.log("in error");
});
};
RegisterController.java
#EnableWebMvc
#RestController
#RequestMapping("/")
public class RegisterController {
#Autowired
private RegisterService registerService;
public RegisterController() {
System.out.println(this.getClass().getSimpleName() + "created..");
}
#ResponseBody
#RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody List<RegisterDTO> stdList) {
System.out.println("inside controller..");
if (stdList != null) {
System.out.println("success...");
}
return registerService.isStudentExist(stdList);
}
}
use JSON Serialization/Deserialization
your request should be
var req = {
method: 'POST', url:'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: JSON.stringify($scope.studentList),
};
your spring controller
#ResponseBody
#RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody string data) {
List<RegisterDTO> stdList = JsonConvert.DeserializeObject<RegisterDTO>(data); // find java jsondeserializer
System.out.println("inside controller..");
if (stdList != null) {
System.out.println("success...");
}
return registerService.isStudentExist(stdList);
}
You are missing contentType: 'application/json' in your request!
RegisterController.js
$scope.submit = function() {
var req = {
method: 'POST',
url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: angular.toJson($scope.studentList),// note this
};
};
download gson jar file.
RegisterController.js
#ResponseBody
#RequestMapping(value = "/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody String data) {
Gson googleJson = new Gson();
ArrayList stdList = googleJson.fromJson(data, ArrayList.class);
if (stdList != null) {
// store your stdList
}
return registerService.isStudentExist(stdList);
}

ajax MVc return to select a single div from return./

I have the below returning an entire page including the partial when it returns from server.
How can I just select a div within the return and disregard the rest?
$('#btnNext').click(function () {
var idVal = parseInt(document.getElementById('pagenumber').value) + 1;
var newPriceVal = 1;
$('#newPart').empty();
$.ajax({
url: '../getMySubjectList',
contentType: 'application/html; charset=utf-8',
data: { catogoryId: newPriceVal, pageid: idVal },
type: 'GET',
dataType: 'html'
})
.success(function (result) {
$('#newPart').html(result);
})
.error(function (xhr, status) {
alert(status);
})
});
You could store the results into a dom element, then read them out by div id.
var domElement = $('<returnedHtml>').append($.parseHTML(result));
var returnDiv = $('#divId', domElement);
$('#newPart').html(returnDiv[0]);
Obviously change #divId to match your returned div.
Your full code would become:
$('#btnNext').click(function () {
var idVal = parseInt(document.getElementById('pagenumber').value) + 1;
var newPriceVal = 1;
$('#newPart').empty();
$.ajax({
url: '../getMySubjectList',
contentType: 'application/html; charset=utf-8',
data: { catogoryId: newPriceVal, pageid: idVal },
type: 'GET',
dataType: 'html'
})
.success(function (result) {
var domElement = $('<returnedHtml>').append($.parseHTML(result));
var returnDiv = $('#divId', domElement);
$('#newPart').html(returnDiv[0]);
})
.error(function (xhr, status) {
alert(status);
})
});

ajax with spring mvc always getting error

Every request ajax getting an error.
Ajax function:
function doAjax() {
var inputText = $("#info").val();
$.ajax({
type: 'POST',
url: 'ajax',
// data: ({text: inputText}),
dataType: 'json',
data: 'text='+inputText,
success: function (response) {
$("#result_info").text(response);
}
error: function (e) {
alert('error' + e.responseText);
}
});
}
Java Controller
#RequestMapping(value = {"/ajax"}, method = RequestMethod.POST)
public #ResponseBody String showText(#RequestParam String text) {
System.out.println(text);
String returnText = "empty";
if (!text.isEmpty()) {
returnText = " response: " + text;
}
return returnText;
}
Besides this question could you tell what is the difference between in ajax query
data: ({text: inputText}),
data: 'text='+inputText,
In this particular case it's better to change dataType to html instead of json. I solved it.

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