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"}
Related
I'm creating an AJAX call that would pass the parameters to the Servlet. However my value displays "null" after debugging. Are both my AJAX and Java Servlet code has missing implementations?
Below is my AJAX implementation :
function getImageDataResponse() {
var isSuccess = false;
var queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const pagePath = urlParams.get('item');
$.ajax({
type: 'POST',
url: '/bin/servlet-demo-path',
data: {urlParams : pagePath},
contentType: 'application/json',
async : false,
success: function (data) {
if(data.imagePath !== null) {
isSuccess = true;
}
},
error: function (error) {
}
});
return isSuccess;
}
This is my Java Servlet implementation:
#Component(service = Servlet.class, property = {
Constants.SERVICE_DESCRIPTION + "=Registered By Path Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths="+ "/bin/servlet-demo-path"})
public class ImageServlet extends SlingAllMethodsServlet {
#Override
protected void doPost(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
String urlPath = req.getParameter("urlParams");
PageManager pM = req.getResource().getResourceResolver().adaptTo(PageManager.class);
Page specificPage = pM.getPage(urlPath);
ValueMap imageMap = specificPage.getProperties("image");
resp.setContentType("application/json");
}
}
This is web code:
DecoupledEditor
.create( document.querySelector( '#webDetails' ),{
language: 'zh-cn',
image: {
toolbar: [ 'imageTextAlternative' ],
styles: [ 'full', 'side' ]
},
ckfinder: {
uploadUrl: '<%=WEBPATH%>/platform/updateMaterial'
}
} )
.then( editor => {
const toolbarContainer = document.querySelector( '#toolbar-webDetails' );
toolbarContainer.appendChild( editor.ui.view.toolbar.element );
} )
This is Spring controller:
#PostMapping("updateMaterial")
#ResponseBody
public String updateMaterial(#RequestParam("upload") MultipartFile file, HttpServletRequest request){
String trueFileName = null;
String realPath = null;
try {
realPath = request.getSession().getServletContext().getRealPath("/upload");
System.out.println(realPath);
trueFileName = uploadImg(realPath, file);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return "{\"default\":\"" + realPath + File.separator + trueFileName + "\"}";
}
Here I return the address of the image on disk.
It is json String style. I want CKEditor 5 api to return the information, but still failure.
What do I need to return in the background to succeed, or am I missing the step?
thank you.
There are many people asking this question, but none of them have a clear solution. Finally, I found it. My code is as follows.
class UploadAdapter {
constructor(loader) {
this.loader = loader;
}
upload() {
return new Promise((resolve, reject) => {
const data = new FormData();
data.append('upload', this.loader.file);
data.append('allowSize', 10);//允许图片上传的大小/兆
$.ajax({
url: 'loadImage',
type: 'POST',
data: data,
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
if (data.res) {
resolve({
default: data.url
});
} else {
reject(data.msg);
}
}
});
});
}
abort() {
}
}
DecoupledEditor
.create( document.querySelector( '#b' ), {
language:"zh-cn"
})
.then( editor => {
const toolbarContainer = document.querySelector( '#a' );
toolbarContainer.appendChild( editor.ui.view.toolbar.element );
// This place loads the adapter.
editor.plugins.get('FileRepository').createUploadAdapter = (loader)=>{
return new UploadAdapter(loader);
};
} )
.catch( error => {
console.error( error );
} );
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}) )
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);
},
});
}
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.