How to send several String to Spring? - ajax

How it's possible to send several string to spring? If I convert several Strings to the Array, I can send, but if I try to send several Strings it's not working. Send Array to Spring not good idea, becouse in Spring I will must use more code (split , new String, etc.)
function sendCustomerInfo() {
var nameCustomerForSend = $("#NickNameCustomerForSend").val();
var phoneCustomerForSend = $("#PhoneCustomerForSend").val();
var emailCustomerForSend = $("#EmailCustomerForSend").val();
var addressCustomerForSend = $("#descriptionCustomerForSend").val();
console.log("Name: " + nameCustomerForSend + " Address: " + addressCustomerForSend + " Phone: " + phoneCustomerForSend
+ " Email: " + emailCustomerForSend);
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST", //это типа method
data: {NickName:nameCustomerForSend, Phone:phoneCustomerForSend, Email:emailCustomerForSend,
description:addressCustomerForSend},
url: '/showAll/customerInfo',
success: function (msg) {
window.location.href = "/showAll"
}
});
}
I receive: Failed to load resource: the server responded with a status of 401 ()
In Spring I try to receive:
#RequestMapping(value = "/showAll/customerInfo", method = { RequestMethod.POST}
, produces = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView showAllForCustomer(#RequestParam(value = "NickName")String name,
#RequestParam(value = "Phone")String phone,
#RequestParam(value = "description")String addressDelivery,
#RequestParam(value = "Email")String email) {
System.out.println("Name: " + name + " Phone: " + phone + " Address: " + addressDelivery + " Email: " + email);
ModelAndView modelAndView = new ModelAndView();
return modelAndView;
}

Use #RequestBody with post and application/json type data
Create DTO having all parameter as you specified in showAllForCustomer
like
public ModelAndView showAllForCustomer(#RequestBody CustomerDto dto){
............
}

Related

Handling a List of Object in AJAX and Spring

I am not able to parse a list of objects in AJAX, Whenever I try to parse the list, ERROR code 406 pops. But if I try to send a string it receives fine.
Controller Code
#RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
#ResponseBody
public List<State> liststates(HttpServletRequest request){
String country = request.getParameter("country");
List<State> states = adminService.getAllstates(Integer.parseInt(country));
System.out.println("The states we recieved is" +states);
String result ="hello Bhaskar "+ country;
return states;
}
JSP AJAX Code
var id = $('#select_country').val();
$.ajax({
url : "getstates",
data: {country : id},
dataType: 'application/json',
type: 'POST',
success : function(response) {
alert("Access Success "+ response);
$('#select_country').append("<option value='-1'>Select User</option>");
for ( var i = 0, len = response.length; i < len; ++i) {
var user = response[i];
$('#select_country').append("<option value=\"" + user.id + "\">" + user.state+ "</option>");
}
},
error : function(response) {
alert("Access Fail "+ response);
}
* Browser Output* Access Failed [object Object]
Open Output Image
* Console Output*
The states we received is [in.complit.model.State#7dee7dc6, in.complit.model.State#54263ffc, in.complit.model.State#43e78960, in.complit.model.State#4ce669b5]
The Problem Solved by adding a try-catch block while calling the service class method in the Controller Class. The code after adding it is as shown below.
#RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
#ResponseBody
public List<State> liststates(HttpServletRequest request){
//List<Country> listCountries = adminService.getAllcountries();
String country = request.getParameter("country");
List<State> states = new ArrayList<State>();
try {
states = adminService.getAllstates(Integer.parseInt(country));
}catch(Exception e) {
System.out.println(e);
}
System.out.println("The Country We Recieved "+ country);
System.out.println("The states we recieved is" +states);
return states;
}

400 Bad Request from a REST Service

I am trying to interact with a REST service by passing Json data to the operation contract URL using AJAX, but I keep getting a Bad Request and don't understand why.
I am cureently coding in Typescript, here is the method to do the Ajax Request:
AjaxLogin = (e: JQueryEventObject) : boolean =>
{
let email = $("#login-email").val();
let pwd = $("#login-pwd").val();
$.ajax({
cache: false,
type: "GET",
url: "http://localhost:57522/PizzaService.svc/Login",
data: '{"email":"' + email + '", "pwd":"' + pwd + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: this.LoginSuccess,
error: this.LoginError
});
e.preventDefault();
return false;
}
The operation contract in the REST service:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/Login")]
Entities.User LoginUser(string email, string pwd);
implemented C# method:
public User LoginUser(string email, string pwd)
{
SqlConnection db;
SqlCommand cmd;
SqlDataReader reader;
db = new SqlConnection(WebConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
cmd = new SqlCommand("SELECT * FROM Customer WHERE customerEmail = #email AND customerPassword = #pwd",db);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#pwd", pwd);
using (db)
{
db.Open();
reader = cmd.ExecuteReader();
if(reader.HasRows)
{
reader.Read();
int id = (int)reader["Id"];
string firstname = reader["customerFirstname"].ToString();
string lastname = reader["customerLastname"].ToString();
int houseno = (int)reader["customerHouseno"];
string postcode = reader["customerPostcode"].ToString();
string tel = reader["customerTel"].ToString();
return new User(id, firstname, lastname, houseno, postcode, tel, email, pwd);
}
else
{
return null;
}
}
}
Thanks, I really appreciate it.

Ajax function returning error calling Spring Controller

Trying to call Spring Controller from jsp code. We are getting a error message Error object [Object]. What's missing ?
JSP code
<script type="text/javascript">
function doAjaxPost() {
// get the form values
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
alert(firstName + " and " + lastName);
$.ajax({
type: "GET",
url: "/DriverController/AddUser",
data: "firstName=" + firstName + "&lastName=" + lastName,
success: function(response){
alert(data);
// we have the aresponse
$('#info').html(response);
$('#firstName').val('');
$('#lastName').val('');
}
,
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Controller Code
package net.codejava.spring;
public class DriverController {
private List<DriverPojoWrapper> userList = new ArrayList<DriverPojoWrapper>();
#RequestMapping(value="/AddUser",method=RequestMethod.GET)
public String showForm(){
System.out.println("Calling DriverController showform /AddUser GET");
return "AddUser";
}
#RequestMapping(value="/AddUser",method=RequestMethod.POST)
public #ResponseBody String addUser(#ModelAttribute(value="user") DriverPojoWrapper driver, BindingResult result ){
String returnText;
if(!result.hasErrors()){
userList.add(driver);
returnText = "User has been added to the list. Total number of users are " + userList.size();
}else{
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value="/ShowUsers.htm")
public String showUsers(ModelMap model){
model.addAttribute("Users", userList);
return "ShowUsers";
}
The servet-controller xml has
<context:component-scan base-package="net.codejava.spring" />

Sending other data besides File in Ajax Post in Spring MVC

I am trying to send some other data with the file in ajax post
var fileInput = document.getElementById('file');
var creditcardid = document.getElementById('creditcardid');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('creditcardid', 'creditcardid');
formData.append('file', file);
$.ajax({
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(response) {
document.getElementById('statusMsg').innerHTML="<fmt:message key="fileUpload.success"/>";
Success();
}
In controller i am writing the code as
#RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public #ResponseBody String fileUpload(#RequestParam(value = "creditcardid")Long creditcardid,#RequestParam(value = "file") MultipartFile file,Model model, HttpServletRequest request) {
String response = "generic.unexpectederror";
try {
model.addAttribute("message", "File '" + file.getOriginalFilename() + "' uploaded successfully");
logger.info("Size of the file is " + file.getSize());
logger.info("Name of the file is " + file.getOriginalFilename());
response = "fileUpload.success";
} catch (DataIntegrityViolationException e) {
response = "fileUpload.error";
logger.error(ExceptionUtils.getStackTrace(e));
}
return response;
}
But my code is not calling controller. Please let me know how to receive both the data and the file. Thanks

Passing jquery object to MVC action

I am trying to use .ajax() to post a People object to a MVC2 action that expects a ViewModel as parameter. The ViewModel has a People property.
The problem is that when the MVC action is activated, the ajax() postback People object is always null. I used Fiddler to diagnose the problem. The property values in the People object are all contained in the header. Here is my client jQuery script. Please note that I used three methods to stuff the property values into People object, but none of them works.
StaffDlg.delegate("#SaveButton", "click",
function (e) {
e.preventDefault();
People["PKey"] = $("#PKey").val();
People["FName"] = $("#FName").val();
People["LName"] = $("#LName").val();
People["MName"] = $("#MName").val();
People["SSN"] = $("#SSN").val();
People["Gender"] = $("#Gender").val();
People["DOB"] = $("#DOB").val();
People["BirthPlace"] = $("#BirthPlace").val();
People["NetworkAccount"] = $("#NetworkAccount").val();
var pkey = $("#PKey").val();
var action;
if (!isNaN(parseFloat(pkey)) && isFinite(pkey)) {
action = "Edit" + "/" + pkey;
}
else {
action = "Create";
}
$.ajax({
url: getRootUrl() + "/Staff/" + action,
//data: { FName: $("#FName").val(), LName: $("#LName").val(), MName: $("#MName").val(),
// SSN: $("#SSN").val(), Gender: $("#Gender").val(), DOB: $("#DOB").val(),
// BirthPlace: $("#BirthPlace").val(), NetworkAccount: $("#NetworkAccount").val()
//},
//data: JSON.stringify(People),
data: $("Form").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (result) {
$("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
},
error: function (qXHR, textStatus, errorThrown) {
$("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
textStatus + ": " + errorThrown + "\r\n" +
"data : " + JSON.stringify(People));
}
})
}
);
and here is the MVC action.
public ActionResult Edit(int id, StaffViewModel updatedStaff)
{
People staff = _staffService.GetStaff(id);
if (updatedStaff == null)
return View("NotFound");
if (ModelState.IsValid)
{
TryUpdateModel<People>(staff, "staff");
staff.RecordLastUpdated = DateTime.Now;
staff.UpdatedBy = HttpContext.User.Identity.Name;
_staffService.SaveStaff();
//return RedirectToAction("Index", new { id = thisStaff.PKey });
if (Request.IsAjaxRequest())
return this.Json(staff, JsonRequestBehavior.AllowGet);
else
{
if (string.IsNullOrEmpty(updatedStaff.previousURL))
return Redirect("/Staff/Startwith/" + staff.LName.Substring(1, 1));
else
return Redirect(updatedStaff.previousURL);
}
}
else
{
if (Request.IsAjaxRequest())
{
string errorMessage = "<div class='whiteOnRed error'>"
+ "The following errors occurred:<ul>";
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errorMessage += "<li>"
+ error.ErrorMessage + "</li>";
}
}
errorMessage += "</ul></div>";
return Json(new { Message = errorMessage });
}
else
return View(updatedStaff);
}
}
You state that the form expects a StaffViewModel as a parameter, and a StaffViewModel has a People property... but you are not passing the full StafFViewModel object - instead you are passing a People object from the Ajax call, and hoping that the People property gets populated on the MVC end.
There is a disconnect there and the auto-binder doesn't know how to bridge it.
Try creating a controller method with a (int, People) signature, and see if that works for you.
Otherwise, you might need to create a custom binder.
Try removing dataType and contentType settings from your ajax call:
$.ajax({
url: getRootUrl() + "/Staff/" + action,
data: $("Form").serializeArray(),
type: "POST",
success: function (result) {
$("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
},
error: function (qXHR, textStatus, errorThrown) {
$("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
textStatus + ": " + errorThrown + "\r\n" +
"data : " + JSON.stringify(People));
}
})
I solved the problem with the .ajax() not posting the form values to the MVC Create(People person) action. It was the parameter type that this different than the one used in Edit(StaffViewModel). Now both action accept the same type of parameter, StaffViewMode.

Resources