spring Model is not filling automatically with json data - java

I have written some sort of code to send data from client to spring model. and want that json data should automatically fill the java class. but not able to do this.
Jquery looks like this
$('#login-form').submit(function(event){
var username = $('#id_username').val();
var password = $('#id_password').val();
alert(username + password)
var json = { "loginId" : username, "password" : password};
$.ajax({
type: "POST",
url: $("#login-form").attr("action"),
data: JSON.stringify(json),
beforeSend: function(xhr){
var mess = validateForm();
if(mess.length != 0){
$('#error-mes').show();
$('#error-mes').html(mess);
event.preventDefault();
return false;
}
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
return true;
},
success: function(response){
$('#error-mes').html(response);
$('#error-mes').show();
},
error: function(e){
alert('Error: ' + e);
}
});
event.preventDefault();
$('#userName').hide();
$('#spn_password').hide();
});
Spring code like this
#RequestMapping(value = "/signin", method = RequestMethod.POST )
public #ResponseBody String submitCustSignInForm(HttpServletRequest request, #ModelAttribute("model") Person model,
HttpSession sess) {
String response = "";
Person person = null;
if (sess.getAttribute("USER_INFO") == null) {
person = tsService.login(model);
if (person == null) {
response = "User name or password does not match.";
} else {
response = "success";
sess.setAttribute("USER_INFO", person);
}
}
return response;
}
Person model has same loginId and password attribute and setter and getter in class.
can some body tell me how can it achieved.

Related

Not getting success response in ajax call, every time going to error function

I am trying to get json data from servlet, from back-end I am getting proper response but every time call is going to error block of ajax call.
Here is My JS Code:
$(document).ready(function()
{
$("#submit").on("click", function()
{
userId = $("#userNameTxt").val();
seqAns = $("#seqAnsTxt").val();
seqQues = $("#seqQues").val();
command = $("#_CMD").val()
alert(command);
$.ajax({
type : "POST",
dataType : "json",
url : "/Inventory/InvController",
data : {_CMD : command, uid : userId, ques : seqQues, ans : seqAns},
success : function(retVal)
{
alert("success");
var test = $.parseJSON(retVal);
if(true)
{
$("#resetPwd").show();
}
},
error: function(error)
{
alert("error");
}
});
});
});
Here is My Servlet Code:
boolean isSuccess = logHelper.performForgotPwdValidation(agentDetails);
PrintWriter out = null;
JsonObject jsonObj = new JsonObject();
try
{
jsonObj.addProperty("isValid", isSuccess);
response.setContentType( "application/json" );
response.setCharacterEncoding("UTF-8");
out = response.getWriter();
out.write(jsonObj.toString());
out.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if( null != out )
{
out.close();
}
}
While running every time it is going to the error function of the ajax call.
please help if I am doing anything wrong.
Thanks in advance.
Your data type is JSON, but your data is just a JavaScript object. Use JSON.stringify() around the data so it's valid JSON data. (Change to JSON.stringify({_CMD : command, uid : userId, ques : seqQues, ans : seqAns}) )

Can't pass a value ajax to servlet

I have a simple code here,
$.ajax({
url: "updateAccount",
type: "POST",
data: {username : "username",pasword:"pasw" , Id : "123"},
success: function(response) {
if (response === "success") {
alert("update success");
location.href = "account.jsp";
loadData();
} else {
alert("update fail");
}
},
error: function() {
alert("execute fail");
}
});
but in my servlet:
if (userPath.equals("/updateAccount")) {
String id = request.getParameter("Id");
String username = request.getParameter("username");
String password = request.getParameter("password");
AccountDTO accountDTO = new AccountDTO();
//accountDTO.setId(id);
accountDTO.setUsername(username);
accountDTO.setPassword(password);
out.print(accountBS.updateAccount(accountDTO));
}
I just only get the value of Id, and username. Value of the parameter password = null.Why and how can i get all of id,username,password values.
Modify the code as follows, Spelling mistake for the key password
data: {username : "username",password:"pasw" , Id : "123"}

How to get JSON response in jQuery Ajax in Spring Mvc? this is my ajax code

How do I get a JSON response in jQuery Ajax in Spring Mvc?
This is my ajax code :
$.ajax({
type: 'POST',
url: "fetch",
dataType: 'json',
data: {clientidedit:clientidedit},
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
Here is my service. this will return a string.How can i get each data in ajax response?
public String getAllClientDetails(String strCode){
// org.json.JSONObject resObjForTable = new org.json.JSONObject();
JSONArray array = new JSONArray();
JSONObject resObj = new JSONObject();
JSONObject resObjPrd = new JSONObject();
SabbModelDet detData = sabbDao.getDataForUpdate(strCode);
List<SabbModelPrd> listPrd = sabbDao.getServicesUpdate(strCode);
//JSONObject resObj = new JSONObject();
String clientId = detData.getClientid();
String clientName = detData.getClientname();
String customerBaseno = detData.getCustomerbaseno();
String category = detData.getCategory_1();
String clientcpt = detData.getClientcpt();
// add PKB and PRK
int fileact = detData.getFileact();
int b2b = detData.getB2b1();
int collection = detData.getCollection1();
String primaccno = detData.getPrimaryaccno();
String accmfromacc = detData.getAccmfromacc();
String accmtoacc = detData.getAccmtoacc();
if (StringUtils.isEmpty(clientId)) {
resObj.put("clientId", org.json.JSONObject.NULL);
} else {
resObj.put("clientId", clientId);
}
if (StringUtils.isEmpty(clientName)) {
resObj.put("clientName", org.json.JSONObject.NULL);
} else {
resObj.put("clientName", clientName);
}
if (StringUtils.isEmpty(customerBaseno)) {
resObj.put("customerBaseno", org.json.JSONObject.NULL);
} else {
resObj.put("customerBaseno",customerBaseno);
}
if (StringUtils.isEmpty(category)) {
resObj.put("category", org.json.JSONObject.NULL);
} else {
resObj.put("category",category);
}
if (StringUtils.isEmpty(clientcpt)) {
resObj.put("clientcpt", org.json.JSONObject.NULL);
} else {
resObj.put("clientcpt",clientcpt);
}
if (fileact>0){
resObj.put("fileact", org.json.JSONObject.NULL);
} else {
resObj.put("fileact",fileact);
}
if (b2b>0){
resObj.put("b2b", org.json.JSONObject.NULL);
} else {
resObj.put("b2b",b2b);
}
if (collection>0){
resObj.put("collection", org.json.JSONObject.NULL);
} else {
resObj.put("collection",collection);
}
if (StringUtils.isEmpty(primaccno)) {
resObj.put("primaccno", org.json.JSONObject.NULL);
} else {
resObj.put("primaccno",primaccno);
}
if (StringUtils.isEmpty(primaccno)) {
resObj.put("accmfromacc", org.json.JSONObject.NULL);
} else {
resObj.put("accmfromacc",accmfromacc);
}
if (StringUtils.isEmpty(accmtoacc)) {
resObj.put(" accmtoacc", org.json.JSONObject.NULL);
} else {
resObj.put(" accmtoacc", accmtoacc);
}
array.put(resObj);
for(int i=1;i<=listPrd.size();i++){
for(SabbModelPrd list:listPrd){
resObjPrd.put("checkservice"+i, list.getServices1());
resObjPrd.put("accountno"+i, list.getAccountno());
resObjPrd.put("translimit"+i, list.getTranscationlimit());
resObjPrd.put("protocol"+i, list.getProtocol1());
resObjPrd.put("clientid"+i, clientId);
resObjPrd.put("productid"+i, list.getProductid());
}
}
array.put(resObjPrd);
// resObjForTable.put("aaData", array);
return array.toString();
Please just add the following in App_Start/WebApiConfig.cs class in my MVC Web API project
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );
You have to have a spring contoller class to access the ajax request and return a model view as the response.
sample controller
#RequestMapping(value="/create", method=RequestMethod.GET)
public ModelAndView createSmartphonePage() {
ModelAndView mav = new ModelAndView("phones/new-phone");
mav.addObject("sPhone", new Smartphone());
return mav;
}
Do a google search on AJAX and Spring to get a lot more examples.
EDIT
A service is not exposed to the controller level so it would be a better option to introduce a controller level.

File download/save from a Jersey rest api call using ANGULARJS . file is attached with response as "Content-Disposition"

I am new to angular .. I hava java rest api which return CSV file in response as attachment as | "Content-Disposition", "attachment; filename=" | content-type :application/octet-stream
Now when i am calling this api from AngularJS using $http i am getting response.data ="" (blank)
I am using basic authorisation for security so I have to pass Header while calling calling API so can't use link click or new window open fro CSV download.
to test when i removed authorisation and hit the url in browser then CSV file is being downloaded.so no issue at server side .
I need help at angularjs side to download CSV file from web api response as attachment.
Here is my Java API Code
public class ServiceAPI {
#GET
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFileAsCSVFile(){
byte[] file=null;
try {
ArrayList<> List=new ArrayList<>();// data retrieved from DB
if(null != List){
file=convertJsonToCSV(new Gson().toJson(List));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.ok(getBytes(file),MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition", "attachment; filename=" + "FileName.csv").build();
}
}
and Angular code :
app.controller('review', ['$scope', '$http', function ($scope, $http){
$scope.fromDate = new Date();
$scope.toDate = new Date();
$scope.minDate = new Date(
$scope.fromDate.getFullYear(),
$scope.fromDate.getMonth() - 2,
$scope.fromDate.getDate(),
$scope.toDate.getFullYear(),
$scope.toDate.getMonth() - 2,
$scope.toDate.getDate()
);
$scope.maxDate = new Date(
$scope.fromDate.getFullYear(),
$scope.fromDate.getMonth() - 2,
$scope.fromDate.getDate(),
$scope.toDate.getFullYear(),
$scope.toDate.getMonth() - 2,
$scope.toDate.getDate()
);
$scope.reviews = json;
function openSaveAsDialog(filename, content, mediaType) {
var blob = new Blob([content], {type: mediaType});
saveAs(blob, filename);
}
function callApi(url) {
// var dat=apiFactory.getServiceData(url);
// console.log(dat);
// apiFactory.getServiceData(url);
var responseType='arraybuffer';
var expectedMediaType='application/octet-stream';
$http.get(url, {
headers: {
accept: expectedMediaType
},
responseType:responseType,
cache: true,
transformResponse: function (data) {
var pdf;
if (data) {
pdf = new Blob([data], {
type: expectedMediaType
});
}
return {
response: pdf
};
}
}).then(function (data,status,headers) {
var filename='Preview.csv',
octetStreamMime = "application/octet-stream",
contentType;
headers = data.headers();
contentType = headers["content-type"] || octetStreamMime;
// openSaveAsDialog(filename, response.data, expectedMediaType);
if (navigator.msSaveBlob) {
var blob = new Blob([data], { type: contentType });
navigator.msSaveBlob(blob, filename);
} else {
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (urlCreator) {
// Try to use a download link
var link = document.createElement("a");
if ("download" in link) {
// Prepare a blob URL
var blob = new Blob([data.data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
} else {
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
var blob = new Blob([data], { type: octetStreamMime });
var url = urlCreator.createObjectURL(blob);
$window.location = url;
}
}
}
});
};
$scope.submit = function (fromDate, toDate) {
$scope.url = API_url;
var resp =callApi(($scope.url).split(" ").join("%20"));
console.log(resp);
};
},
]);
I have an example with spring MVC instead of JAX-RS (Jersey)
HTML:
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
Angularjs controler:
$scope.downloadCsv = function () {
console.log("downloadCsv");
var fileName = "test.csv";
var a = document.createElement("a");
document.body.appendChild(a);
XxxxxxServiceCSV.downloadCsv().then(function (result) {
console.log("downloadCsv callback");
var file = new Blob([result.data], {type: 'application/csv'});
var fileURL = URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
Angularjs services:
angular.module('xxxxxxxxApp')
.factory('XxxxxxServiceCSV', function ($http) {
return {
downloadCsv: function () {
return $http.get('api/downloadCSV', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Java code JAX-RS(spring MVC):
#RequestMapping(value = "/downloadCSV", method = RequestMethod.GET, produces = "application/csv")
public void demo(HttpServletResponse response) throws IOException {
List<String> names = new ArrayList<String>();
names.add("First Name");
names.add("Second Name");
names.add("Third Name");
names.add("Fourth Name");
BufferedWriter writer = new BufferedWriter(response.getWriter());
try {
response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");
for (String name : names) {
writer.write(name);
writer.write(",");
}
writer.newLine();
} catch (IOException ex) {
} finally {
writer.flush();
writer.close();
}
}

Display exception's message from Controller MVC in the jsp page

StudentController - here is my controller class that returns exceptions and i want to handle and display these in jsp
#RequestMapping(value = RequestURL.ADD_STUDENT, method = RequestMethod.POST)
#ResponseBody
public void addStudent(#RequestBody AddStudentRequest addStudentRequest) throws StudentGroupNumberNotFoundException, SpecializationNotFoundException {
User user = new User(addStudentRequest.getUsername(),
addStudentRequest.getPassword(), Role.ROLE_STUDENT);
userService.add(user);
user = userService.findByUsername(addStudentRequest.getUsername());
int userId = user.getId();
try {
int groupId = studentGroupService
.getIdByGroupNumber(addStudentRequest.getGroup());
int specializationId = specializationService
.getIdByName(addStudentRequest.getSpecialization());
Student student = new Student(userId, specializationId,
addStudentRequest.getName(),
addStudentRequest.getRegistrationNumber(), groupId,
addStudentRequest.getYear());
studentService.add(student);
} catch (StudentGroupNumberNotFoundException e) {
throw new StudentGroupNumberNotFoundException(e.getMessage());
} catch (SpecializationNotFoundException e) {
throw new SpecializationNotFoundException (e.getMessage());
}
}
student.jsp - jsp page for student
function addStudent() {
var username = $('#modalStudentUsername').val();
var password = $('#modalStudentPassword').val();
var name = $('#modalStudentName').val();
var registrationNumber = $('#modalStudentRegistrationNumber').val();
var group = $('#modalStudentGroup').val();
var year = $('#modalStudentYear').val();
var specialization = $('#modalStudentSpecializationId').val();
var data = '{ "username" : "' + username + '", "password": "'
+ password + '", "name":"' + name
+ '","registrationNumber": "' + registrationNumber + '" , "specialization": "' + specialization
+ '","group": "' + group+'", "year": " ' + year + '" }';
var token = $('#csrfToken').val();
var header = $('#csrfHeader').val();
$.ajax({
type : "POST",
url : "student/add",
contentType : 'application/json',
data : data,
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader(header, token);
},
success : function(data, status, xhr) {
alert("Success!");
},
error : function(xhr, status, errorThrown) {
alert("Error!");
},
});
}
I want to display in the alert from ajax the exception's message from controller. Could anyone help me? Thanks!
Change the method return type from void to String & give a call to xhr.responseText in alert() just like below:-
Change In Controller:
#ResponseBody
public void addStudent(#RequestBody AddStudentRequest addStudentRequest) throws StudentGroupNumberNotFoundException, SpecializationNotFoundException {
// business logic
}
to
#ResponseBody
public String addStudent(#RequestBody AddStudentRequest addStudentRequest) throws StudentGroupNumberNotFoundException, SpecializationNotFoundException {
// business logic
}
Change In JavaScript:
function addStudent() {
// ...
$.ajax({
type : "POST",
url : "student/add",
contentType : 'application/json',
data : data,
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader(header, token);
},
success : function(data, status, xhr) {
alert(xhr.responseText);
},
error : function(xhr, status, errorThrown) {
alert(xhr.responseText);
},
});
}

Categories

Resources