I developed a message system and in the inbox I want to delete multiple messages selecting it with some checks and calling the delete method but I don't know if I can do it witout a form. Some people tells me that I can do with JQuery but I don't know how to do.
MessagesController.java
#RequestMapping(value = "/mensajes/delete/{menssageId}")
public String menssagesDelete(final ModelMap model, #PathVariable("menssageId") final Integer mensajeId,
final HttpServletRequest request, final RedirectAttributes redirectAttrs) {
final User user = (User) request.getSession().getAttribute(Constantes.SESSION_USER_KEY);
final Mensajes mensaje = this.mensajesService.loadMensaje(mensajeId);
this.mensajesService.deleteMensaje(mensaje);
return "redirect:/menssages/home";
}
EDIT:
Now I have this:
MessagesController.java
#ResponseBody
#RequestMapping(value = "/mensajes/deleteMensajes.json", method = RequestMethod.GET, headers = "Accept=application/json")
public void deleteMensajes(final String[] arrayMensajes) {
}
And this is de js code:
function eliminarMensajes(){
var arrayMensajesSeleccionados = jQuery('[name="msgIdRecibido"]:checked').map(function () {
return this.value;
}).get();
//Llamada ajax
$.ajax({
type: "GET",
url: "deleteMensajes.json",
data:{'arrayMensajes': arrayMensajesSeleccionados},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("hola");
}
});
When enter the controller method the arrayMensajes is null What Im doing wrong?
It works when add this to controller
public void deleteMensajes(#RequestParam(value="arrayMensajes[]", required=false) final String[] arrayMensajes)
Related
i tried accessing my controller through ajax to get DB results but it wont work. The ajax is inside a submit button and executes well without the ajax. The code is supposed to execute a query and check if the input exists.
Here's my ajax
var jsonData = {
"appname": appname,
"txtype": txtype,
"ipaddress": ipaddress
};
$.ajax({
type: 'POST',
url: "checkaccesspermission.html",
data: jsonData,
success: function(data) {
if(data == "exists"){
alert('Permission Already Exists!');
return false;
}else{
alert('Add Permission test Succesful!');
return true;
}
},
async: false
});
here's my controller
#RequestMapping(value="/checkaccesspermission", method=RequestMethod.GET)
public String checkaccesspermission(#ModelAttribute("loginForm") IpAccessManagementModel loginForm, Model model,
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID) throws IOException{
System.out.println("CHECKACCESSPERMISSIONs");
IpAccessManagementModel sub = new IpAccessManagementModel();
//System.out.println("<script language='JavaScript'>alert('Hello');</script>");
sub.setAppName(appID);
sub.setTxtType(txtype);
sub.setIpAddress(ipaddress);
System.out.println(ipaddress);
ipAccessMGTDAO.addPermission(sub);
String resultCheckExist = ipAccessMGTDAO.checkAccessPermission(sub);
return resultCheckExist;
}
Remove the .html extension and Change your method annotation in the controller to method=RequestMethod.POST
also remove
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID
because its a Post request
I know that this question has been asked many times, but I have looked at every variation I could find and have still not been able to find out my issue.
Here is my ajax call:
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
contentType: "application/json",
data: JSON.stringify(input),
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
The endpoint works. You can take my word for it.
Spring controller:
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
And here is my model class:
public class FormInput {
private String userInputOne;
private String userInputTwo;
private String userInputThree;
private String userInputFour;
private String userInputFive;
public FormInput(String userInputOne, String userInputTwo, String userInputThree, String userInputFour, String userInputFive) {
this.userInputOne = userInputOne;
this.userInputTwo = userInputTwo;
this.userInputThree = userInputThree;
this.userInputFour = userInputFour;
this.userInputFive = userInputFive;
}
public String getUserInputOne() {
return this.userInputOne;
}
public String getUserInputTwo() {
return this.userInputTwo;
}
public String getUserInputThree() {
return this.userInputThree;
}
public String getUserInputFour() {
return this.userInputFour;
}
public String getUserInputFive() {
return this.userInputFive;
}
}
I keep getting a HTTP status code of 415, which means unsupported media type. I set the contentType to "application/json", and I also tried to add "consumes= 'application/json'" to my Spring controller and that didn't help either. Thank you for any help you can give.
EDIT: I am now getting the following error after changing RequestMethod.GET to RequestMethod.POST: "Error 405: Request method 'GET' not supported"
There is no need to send parameter as json,you have made things complicated
In javascript code,you can remove contentType: "application/json", and change the format of data property to send data directly
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
//contentType: "application/json",
data: input,//send data directly
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
In java code,you can remove #ResponseBody annotation before FormInput
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
The java controller method you have written is of type 'GET', it should be changed to 'POST', as the ajax call you are making is also of type POST
Try this and it will work
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
I guess main problem in not match http methods. You sent by POST method, but controller wait for GET method.
This is because your method signature doesn't match. Just remove contentType: "application/json".
I'm trying to execute my controller and get the return string to be used for my alert message, but my success function won't work. It executes the controller but does not execute the success function. The error executes but does not display any message.
BELOW IS THE AJAX
var jsonData = {
"appIDHidden": appname,
"txtypeHidden": txtype,
"ipaddress": ipaddress
};
$.ajax({
type: 'POST',
url: "checkaccesspermission",
data: jsonData,
dataType: 'json',
success: function(data) {
if(data != "exists"){
alert('Permission Already Exists!');
return false;
}else{
alert('Add Permission test Succesful!');
return true;
}
alert('test123');
},
error: function(jqXHR, textStatus, thrownError)
{
alert(thrownError+jsonData[1]);
},
async: false
});
BELOW IS THE CONTROLLER
#RequestMapping(value="/checkaccesspermission", method=RequestMethod.POST)
public String checkaccesspermission(#ModelAttribute("loginForm") IpAccessManagementModel loginForm, Model model,
HttpSession session, BindingResult result,HttpServletRequest request,
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID) throws IOException{
System.out.println("CHECKACCESSPERMISSIONs");
IpAccessManagementModel sub = new IpAccessManagementModel();
sub.setAppName(appID);
sub.setTxtType(txtype);
sub.setIpAddress(ipaddress);
System.out.println(ipaddress);
ipAccessMGTDAO.addPermission(sub);
String resultCheckExist = ipAccessMGTDAO.checkAccessPermission(sub);
System.out.println("checkResult:|"+resultCheckExist+"|");
return resultCheckExist;
}
Nevermind, i got it to work by adding #public ResponseBody on my Controller :#RequestMapping(value="/checkaccesspermission", method=RequestMethod.POST)
public #ResponseBody
String checkaccesspermission
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.
I have the page about.ftl which is invoked when I type localhost:8080/ui/about
and I have put the following block of code inside. Through SendToServlet() function I am trying to send the user info to my controller which is the OAuthController.java
function SendToServlet(){
$.ajax({
url: "localhost:8080/ui/about",
type: "POST",
data: JSON.stringify({ user:jsonObj}),
contentType: 'application/json',
success: function(result) {
alert(done);
},
error: function(xhRequest, ErrorText, thrownError) {
alert(JSON.stringify(jsonObj));
}
});
}
</script>
My Spring MVC Controller class code has the following implementation - all that it does is that it accepts the user's information and then sets up current user:
#Controller
#RequestMapping("/about")
public class OAuthController {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String post( #RequestBody String items, HttpServletRequest request, HttpServletResponse response)
{
String jsonResp = items;//sb.toString();
ArrayList<String> usercredentials = new ArrayList<String>();
usercredentials = parseJson(jsonResp);
UserMethods usermethods = new UserMethods();
usermethods.setCurrentUser (usercredentials);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
return "{\"success\":\"\"}";
}
public ArrayList<String> parseJson(String json){
}
}
My problem is that the controller is never invoked and actually I never see a Post request to be sent anywhere through Firebug. I've spent several days on it, but still no luck. Do you have any suggestions?
You need to bind value with your function. Your url localhost:8080/ui/about/post is just used to locate the controller but it will not execute any function because you didn't make a call to any function.
To call the function, you have to do like this :
#RequestMapping(method = RequestMethod.POST, value ="/anyValue")
public String anyFunctionName(anyParam){...}
Above function will bind to url localhost:8080/ui/about/anyValue.
Don't you need to call it like this?
url: "localhost:8080/ui/about/post",
but first do this:
#RequestMapping(method = RequestMethod.POST, value = "/post")
How about try to add .html?Application won't add it automatically.