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);
},
});
}
Related
I've a problem with call WS Rest Java. I call the WS but the parameters isn't passed.
My java code:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response setUser(#FormParam("name") String name, #FormParam("surname") String surname, #FormParam("email") String email,
#FormParam("phone") String phone, #FormParam("skype") String skype, #FormParam("password") String password){
try {
FileOutputStream fis = new FileOutputStream("/home/File.txt");
PrintStream ps = new PrintStream(fis);
String s = "name: "+name+"\nSurname: "+surname+"\nEmail: "+email+"\nPhone: "+phone+"\nSkype: "+skype+"\nPassword: "+password;
ps.println(s);
ps.close();
fis.close();
UserDAO userdao = new UserDAO(0,name,surname,email,phone,skype);
userdao.save();
...
return Response.status(200).entity(new ObjectMapper().writeValueAsString("OK!")).header("Access-Control-Allow-Origin", "*").build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("ERROR!").header("Access-Control-Allow-Origin", "*").build();
}
}
Angular call:
data = {
name: $scope.reg_name,
surname: $scope.reg_surname,
email: $scope.reg_email,
phone: $scope.reg_phone,
skype: $scope.reg_skype,
password: $scope.reg_password
}
$http.post(baseUrl+'user/',data,{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
If i log data on angular data are set, the call working but i've an error when i create AccountDAO object because the parameters are null. To test the parameters values i create a file and put here the value, the content are this:
name: null
Surname: null
Email: null
Phone: null
Skype: null
Password: null
Any one have idea why not pass the parameters?
Thanks!
Solved:
data = "name=" + $scope.reg_name +
"&surname=" + $scope.reg_surname +
"&email=" + $scope.reg_email +
"&phone=" + $scope.reg_phone +
"&skype=" + $scope.reg_skype +
"&password=" + $scope.reg_password;
}
$http.post(baseUrl+'user/',data,{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
Thanks grizzly!
You are sending data as JSON. Change it to form data string:
data = "name=" + $scope.reg_name +
"&surname=" + $scope.reg_surname +
"&email=" + $scope.reg_email +
"&phone=" + $scope.reg_phone +
"&skype=" + $scope.reg_skype +
"&password=" + $scope.reg_password;
}
$http.post(baseUrl+'user/',data,{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
data passed in uploadData function contains below value:
lastModified:1478845421494
lastModifiedDate:Fri Nov 11 2016 11:53:41 GMT+0530 (India Standard Time)
name:"u_ex150626.log"
size:2022067
type:""
webkitRelativePath:""
__proto__:File
In service.js:
function($http, $q) {
return {
uploadData : function(baseUrl, data) {
var fd = new FormData();
/*for(var key in data)
fd.append(key,data[key]);*/
fd.append("file", data);
console.log('fd:' + fd);
var name="Meenu";
return $http.post(baseUrl+'/data/fileupload', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).then(
function successCallback(response){
alert('Response: '+response.data);
},function errCallback(errResponse){
alert('Error: '+errResponse.data);
alert('Error: '+errResponse.status);
});
},
}
}
In controller.java:
#RequestMapping(value = "/data/fileupload", method = RequestMethod.POST)
#ResponseBody
public String postFile(#RequestParam(value = "file",required=false) MultipartFile file) {
try {
System.out.println("name = " + file);
} catch (Exception e) {
e.printStackTrace();
}
return "OK";
}
I am getting null value for 'file'. Please let me know how can we receive the file from http request in controller.java.
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"}
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.
I have implemented a RESTful web Service in java which inserts data into MySQL db, I have tested this using POSTER in mozila firefox and also in google chrome. My Web Service takes a String with the POST request, now I am unable to utilize WEB SERVICE using JS: the code making POST request on WEB SERVICE URL is as follows:
$.ajax({
url: 'http://localhost:8080/AgentWS/webresources/Items',
type: 'POST',
contentType: 'application/xml',
dataType: 'xml',
data: 'content='+content,
success: function (data) {
alert(content);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
The alert in success function is also not displayed plus the dialog error is showing a dialog with : Error: on it'
Server Side code is:
#POST
#Consumes("application/xml")
#Produces("application/xml")
public String postXml(String content) {
//TODO
// return Response.created(context.getAbsolutePath()).build();
StringTokenizer sp = new StringTokenizer(content, "&");
String agentName = sp.nextToken();
String agentId = sp.nextToken();
String agentState = sp.nextToken();
String agentExtension = sp.nextToken();
String agentDeviceState = sp.nextToken();
String agentDeviceStateChangeTime = sp.nextToken();
DBConection conn = new DBConection();
conn.insertAgentActivityInfo(agentName, agentId, agentState, agentExtension, agentDeviceState, agentDeviceStateChangeTime);
return agentName + " " + agentId + " " + agentState + " " + agentExtension + " " + agentDeviceState + " " + agentDeviceStateChangeTime;
}
I think the problem is with the data you are sending,
data: 'content='+content should be replaced with a name for the parameter like
data: {content:'content='+content}
and check what you are doing on the server side
My guess is that data: 'content='+content, is posting invalid XML to the server and you are getting 500 Internal Server Error. Can you try setting the data to just the XML content? like
...
data: content,
....
EDIT
If all you want is a simple post
Java
#POST
public String postXml(String content) {
//TODO
// return Response.created(context.getAbsolutePath()).build();
StringTokenizer sp = new StringTokenizer(content, "&");
String agentName = sp.nextToken();
...
return agentName + " " + agentId + " " + agentState + " " + agentExtension + " " + agentDeviceState + " " + agentDeviceStateChangeTime;
}
Javascript
$.ajax({
url: '/AgentWS/webresources/Items',
type: 'POST',
data: 'content=1&2&3&4&5&5',
success: function (data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
Here's what i think, you should write a model class Agent in server side like this :
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Agent
{
private String agentName;
private String agentId;
private String agentState;
private String agentExtension;
private String agentDeviceState;
private String agentDeviceStateChangeTime;
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getAgentId() {
return agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
public String getAgentState() {
return agentState;
}
public void setAgentState(String agentState) {
this.agentState = agentState;
}
public String getAgentExtension() {
return agentExtension;
}
public void setAgentExtension(String agentExtension) {
this.agentExtension = agentExtension;
}
public String getAgentDeviceState() {
return agentDeviceState;
}
public void setAgentDeviceState(String agentDeviceState) {
this.agentDeviceState = agentDeviceState;
}
public String getAgentDeviceStateChangeTime() {
return agentDeviceStateChangeTime;
}
public void setAgentDeviceStateChangeTime(String agentDeviceStateChangeTime) {
this.agentDeviceStateChangeTime = agentDeviceStateChangeTime;
}
}
And the server rest service that you have should be changed little bit :
#POST
#Consumes("application/xml")
#Produces("application/xml")
public String postXml(Agent agent) {}
Inside this method you can use "agent" object, that is passed, to retrieve all the values sent by the client like agent.getAgentName()
Now the payload(or request body) that should contain something like this:
<Agent>
<agentName></agentName>
<agentId></agentId>
<agentState></agentState>
<agentExtension></agentExtension>
<agentDeviceState></agentDeviceState>
<agentDeviceStateChangeTime></agentDeviceStateChangeTime>
</Agent>
I hope it is of some assistance.
Hard to guess without the error code and message but:
change
data: 'content='+content
to
data: { content : content } // format as json
And in your java resource:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public String postXml(String content)
// read content as json