JSP Multiple Buttons with Different API in Single Form - java

I was having some problem when trying to put multiple buttons in one JSP form.
<form:form action="/search" method="POST">
<tr>
<td align="left">
<input type="button" onclick="valSubmit('doImageExtractSearchList', this.form);" value="Image Extract" />
</td>
<td align="right">
<input type="button" onclick="valSubmit('doCardIssueSearchList', this.form);" value="Card Search" />
</td>
</tr>
</form:form>
In my controller class, how can I differentiate it comes from which button and specify the API?
#RequestMapping(value = "/search", method = { RequestMethod.POST })
public String doSubmit() {
return "";
}
#RequestMapping(value = "/imageExtract", method = { RequestMethod.POST })
public String doSubmit() {
return "";
}
#RequestMapping(value = "/cardSearch", method = { RequestMethod.POST })
public String doSubmit() {
return "";
}
Thanks!

Since you already trigger a function call on click , why don't you use the function to make an Ajax call to the backend api . That way you could provide separate url for the POST call depending upon the parameter passed into the jquery method like :
function valSubmit(value, form) {
var url;
if(value == "doImageExtractSearchList") {
url = "http://something/search/imageExtract";
}
else if(value == "doCardIssueSearchList") {
url = "http://something/search/cardExtract";
}
var form = $('#formId');
var data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
}

Related

Ajax POST delete multiple items with the same name Spring MVC

I'm trying to delete multiple Items with the same name in my web app. But it's giving me an error 500 when I do the POST.
This is my Form Code
<form method="POST" name="deleteFormAdd" id="deleteFormAdd" enctype="multipart/form-data">
<input type="hidden" name="_csrf" th:value="${_csrf.token}" />
<!--Asset ID set to hidden so the User can't see it-->
<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
th:name="assetID"
th:value="${deleteCategory.assetID}"/>
<!-- For showing all the Asset to be deleted -->
<input class="w3-input w3-border w3-round-large" type="text"
th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
th:name="${DeleteCategoryObject[__${itemStat.index}__].assetType}"
th:value="${deleteCategory.assetType}"
disabled="disabled"/>
<br></br>
<input type="button" class="btn btn-primary btn-block" value="Yes" th:onclick="'javascript:submitForm(\'deleteFormAdd\',\''+#{/delete-asset}+'\')'" />
<button type="reset" onclick="window.location.href = 'manage-assets.html';" class="btn btn-default btn-block"> Cancel</button>
</form>
Submit Form Ajax
function submitForm(formID, url){
var formData = new FormData($("#" + formID)[0]);
$.ajax({
dataType: 'json',
url: url,
data : formData,
type : "POST",
enctype : "multipart/form-data" ,
processData : false,
contentType : false,
success : function(data) {
if (data.status == 1) {
openAlertDialog("Success", "The Asset type has been deleted!", "Continue", "manage-assets");
} else {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
}
},
error : function(data) {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
},
});
}
Spring Controller
#RequestMapping(value = "/delete-asset", method = RequestMethod.POST)
public #ResponseBody String deleteAsset(#ModelAttribute List<AssetCategory> assetCategories) {
JsonObject result = new JsonObject();
if (assetCategories != null && !assetCategories.isEmpty()) {
String[] arr = new String[assetCategories.size()];
for (int i =0; i < assetCategories.size(); i++) {
arr[i] = assetCategories.get(i).getAssetID();
}
assetService.deleteAssets(arr);
result.addProperty("result", "Success");
result.addProperty("status", 1);
result.addProperty("message", "Asset Deleted!");
}
return result.toString();
}
Spring Service
#Override
public AssetCategory deleteAssets(String[] assetID) {
return dao.deleteAssets(assetID);
}
Spring DAO
#Query("Delete From AssetCategory A WHERE A.assetID IN (:assetID)")
public AssetCategory deleteAssets(#Param("assetID") String[] assetID);
Spring Console Error
Failed to instantiate [java.util.List]: Specified class is an interface] with root cause
org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface
This is the Form Data (it contains the asset ID's)
Seems issue with your ajax function. Check with below:
function submitForm(formID, url) {
var assetIdList = [];
var assetIdObj;
$("#" + formID).find('input[name="assetID"]').each(function () {
assetIdObj = {};
assetIdObj.assetID = $(this).val();
assetIdList.push(assetIdObj);
});
$.ajax({
dataType: 'json',
url: url,
data: {assetCategories: assetIdList},
type: "POST",
enctype: "multipart/form-data",
processData: false,
contentType: false,
success: function (data) {
if (data.status === 1) {
openAlertDialog("Success", "The Asset type has been deleted!", "Continue", "manage-assets");
} else {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
}
},
error: function (data) {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
},
});
}
Update this html code from:
<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
th:name="assetID"
th:value="${deleteCategory.assetID}"/>
To this:
<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
name="assetID"
th:value="${deleteCategory.assetID}"/>
You are using multipart/form-data. So, your request header has multipart/form-data Content-Type which have data as form type. like key=value.
So just remove #ModelAttribute annotation and add consumes properties to your mapping annotation.
//if you're using spring version more than 4.3, use below #PostMapping for readability
//#PostMapping(value = "/delete-asset", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
#RequestMapping(value = "/delete-asset", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public #ResponseBody String deleteAsset(List<AssetCategory> assetCategories) {
JsonObject result = new JsonObject();
//you can use apache's commons-collection
if (CollectionUtils.isNotEmpty(assetCategories)) {
//and you can also use stream api
String[] arr = assetCategories.stream()
.map(AssetCategory::getAssetID)
.toArray();
assetService.deleteAssets(arr);
result.addProperty("result", "Success");
result.addProperty("status", 1);
result.addProperty("message", "Asset Deleted!");
}
return result.toString();
}

How to upload form with image file in it, AngularJS spring

I have this form
<div class="row">
<h1 class="page-header">
Create
</h1>
<form ng-submit="create()", enctype="multipart/form-data">
<div class="form-group">
<label>Name:</label>
<input type="text" ng-model="subforum.name" class="form-control" />
</div>
<div class="form-group">
<label>Desc:</label>
<input type="text" ng-model="subforum.desc" class="form-control" />
</div>
<input type="file" ngf-select ng-model="subforum.icon" name="subforum.icon"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<img ng-show="myForm.file.$valid" ngf-thumbnail="subforum.icon" class="thumb"> <button ng-click="subforum.icon= null" ng-show="subforum.icon">Remove</button>
<button class="btn btn-success" type="submit">Create</button>
</form>
``
In my JS
.config(function($stateProvider) {
$stateProvider.state('create', {
url:'/subforum/create',
views: {
'main': {
templateUrl:'subforum/create.tpl.html',
controller: 'CreateCtrl'
}
},
data : { pageTitle : "Create Subforum" }
})
and
.factory('subforumService', function($resource) {
var service = {};
service.create = function (subforum, success, failure) {
var SubForum= $resource ("/web-prog/rest/subforums");
SubForum.save({}, subforum, success, failure) ;
};
.controller("CreateCtrl", function($scope, $state, subforumService) {
$scope.create = function() {
$scope.subforum.author = JSON.parse(localStorage.getItem ("logedUser"));
subforumService.create($scope.subforum,
function(returnedData) {
$state.go("home");
},
function() {
alert("Error creating");
});
};
I know thats not best practice to save user in LocalStorage but for now its like that.
On backend i have controller and in that controller i have methode:
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<SubForumResource> createPodforum(#RequestBody SubForumResource sentPodforum) {
}
and SubForumResource is
public class PodforumResource extends ResourceSupport {
private String name;
private String desc;
private byte[] icon;}
with geters and seters and everything i need.
So when i have form without image it works without problems. But i need icon too. Im new to angularjs but need it for this project. When i try to use FormData() i dont know how to use $resource. So if someone can help me i would be thankful. This is my first prject i need to work front end so im lost.
You can refer below code for angularjs :
this.addEmployee = function (requestData, file) {
var data = new FormData();
data.append('file', file[0]);
data.append('requestData', new Blob([JSON.stringify(requestData)], {
type: "application/json"
}));
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
var url = "http://localhost:8080/addEmployee";
var promise1 = $http.post(url, data, config);
var promise2 = promise1.then(function (response) {
return response.data;
},
function errorCallback(response) {
alert(response.data.errorMessage);
});
return promise2;
}
And for controller :
#RequestMapping(value = "/addEmployee", method = RequestMethod.POST, consumes = {"multipart/form-data" })
#CrossOrigin
public CustomResponse addEmployee(#RequestPart("file") MultipartFile file, #RequestPart("requestData") Employee emp) {
}

Spring - form with 2 buttons sending to 2 different controllers

I have Spring 4 MVC form with 2 submit buttons. I want these buttons to point to two different controllers. The problem is that one form should have fixed action parameter set.
This is my form:
<form:form method="post" action="pageAction" commandName="id">
<button type="submit" class="btn btn-primary" name="addBasket">
Add Basket
</button>
<button type="submit" class="btn btn-danger" name="addProduct">
Add Product
</button>
</form:form>
Is it possible that these button will reach two different controllers? I am going to send only ID, in addBasket it would be basketId, in addProduct it would be productId. These are the controllers:
#Controller
public class BasketController {
#RequestMapping(value = "/addBasket", method = RequestMethod.POST)
public ModelAndView addBasket(#ModelAttribute("id") Integer id) {
//method - addBasket(id);
}
}
#Controller
public class ProductController {
#RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public ModelAndView addProduct(#ModelAttribute("id") Integer id) {
//method - addProduct(id);
}
}
If you are using html 5 and compatible browsers, you can use form and formaction attributes of buttons to target according to your needs. See details at w3schools
I am not sure if there is a solution you want, but an alternative might be to use an if statement in /addItem checking the value of name:
#Controller
public class ItemController {
#RequestMapping(value = "/addItem", method = RequestMethod.POST)
public ModelAndView addItem(#ModelAttribute("id") Integer id, #ModelAttribute("name") String name) {
if ("basket" == name) {
basketController.addBasket(id);
} else {
productController.addProduct(id);
}
}
}
You can add an onclick event on the submit button, which would call the a javascript function wherein you could decide/change the url as per the requirement.
<button type="submit" class="btn btn-primary" name="addBasket" onClick="javascript:addBasket()">
<button type="submit" class="btn btn-primary" name="addProduct" onclick="javascript:addProduct()">
Add any number of javascript functions like:
function addBasket() {
var requestURL = '/addBasket';
var formData = $("#formName").serialize();
$.ajax({
type: 'POST',
data: formData,
url: requestURL,
success: function (data1) {
//do what is required after success
},
error: function (xhr) {
//in case of failure
}
});
}

in spring framework how to get response from controller to jsp page by ajax call passing an id value to controller

In my program i need to perform an operation by passing id.The id is selected from a dropdown box(ie;changing dynamically).so to pass the id i'am using ajax.but i don't know the code to receive the response back from controller in spring.
<div class="form-group">
<label class="col-sm-4 control-label">Employee</label>
<div class="col-sm-6">
<select id="empId" name="empId" class="form-control" >
<option value="" >--Select--</option>
<c:forEach var="row" items="${employeeList}" >
<option value="${employeeList.Id}">${employeeList.name</option>
</c:forEach>
</select>
</div>
<div class="col-sm-6">
<input type="text" name="empname" id="empname" class="form-control"/>
</div>
</div>
//i need to pass the employee id from the dropdown box to controller and get //the name of the employee as response .and set the response value in the text //box.how can be it done in spring using ajax.
//ajax code i tried
$('#empId').change(function(event) {
var eId= $("select#empId").val();
$.get('getEmpName', {
id: eId
}, function(data) {
$('#empname').val(data);
});
});
//but i am not getting any response ie:nothing in data
Here the ajax side code:
$('#empId').change(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'your_url', // in your controller side (RequestMapping value)
data: 'empId='+$('#empId').val(),
success: function(responseData, textStatus) {
// your stuff here. you found the response in responseData var.
},
complete: function(textStatus) {
},
error: function(responseData)
{
}
});
});
And your controller side code like something below,
#RequestMapping(value = "your_url", method = RequestMethod.POST)
public ResponseEntity<String> postMethod(HttpServletRequest req) {
String jsonString = "";
String empId = req.getParameter("empId");
// your operation done here and
//convert it to json format before sending response.
jsonString = gson.toJson("your response convert here to json format"); // here i used google Gson library to convert your response in json format.
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");
return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
}

jQuery+Spring remove from database

I have a project using Spring and i need to create admin page using jQuery. I have a table with all users and i have a button "delete". When i click it user should be deleted from the database. Without script everything works fine but with script i can't figure out how do i make user deleted from database and how to send user login to controller. I could only remove row from table, but when i refresh the page user is still there.
Could anyone please help me how to delete user from db within script?
Table
<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">
<tr>
<th>Login</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birthday</th>
<th>Role</th>
<th>Actions</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.login}</td>
<td>${user.firstname}</td>
<td>${user.lastname}</td>
<td>${user.birthday}</td>
<td><c:if test="${user.roleid==1}">Admin</c:if>
<c:if test="${user.roleid==2}">User</c:if></td>
<td>Edit
<a class="confirm" href="delete/${user.login}">Delete</a></td>
</tr>
</c:forEach>
</table>
Controller without script(it's commented now, but it works fine)
#RequestMapping("/delete/{userLogin}")
public String deleteUser(#PathVariable("userLogin") String userLogin) {
userService.remove(userService.findByLogin(userLogin));
return "redirect:/welcome";
}
Controller for script
#Controller
public class SpringController {
#Autowired
private UserService userService;
#RequestMapping(value = "/delete/{userLogin}", method = RequestMethod.POST)
#ResponseBody
public boolean updateUser(#RequestParam("userLogin") String userLogin) {
userService.remove(userService.findByLogin(userLogin));
return true;
}
}
Script
<script>
$(document).ready(function() {
$("#userBase .confirm").on("click",function() {
var conBox = confirm("Are you sure ?");
if(conBox){
var tr = $(this).closest('tr');
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();
});
} else {
$(this).dialog("close");
}
});
});
</script>
Here's what worked for me:
Table (check "Delete" link)
<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">
<tr>
<th>Login</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birthday</th>
<th>Role</th>
<th>Actions</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.login}</td>
<td>${user.firstname}</td>
<td>${user.lastname}</td>
<td>${user.birthday}</td>
<td><c:if test="${user.roleid==1}">Admin</c:if>
<c:if test="${user.roleid==2}">User</c:if></td>
<td>Edit
Delete
</tr>
</c:forEach>
</table>
Controller
#RequestMapping(value="/delete/{userLogin}", method=RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void deleteUser(#PathVariable String userLogin) {
userService.remove(userService.findByLogin(userLogin));
}
Script
<script>
$(document).ready(function() {
var deleteLink = $("a:contains('Delete')");
$(deleteLink).click(function(event) {
var conBox = confirm("Are you sure ?");
if(conBox){
$.ajax({
url: $(event.target).attr("href"),
type: "DELETE",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function() {
var tr = $(event.target).closest("tr");
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();})
}
});
} else {
event.preventDefault();
}
event.preventDefault();
});
});
</script>
On your code, you are not calling the needed url to call the handler method that will delete the user. I assume you want to do this using ajax? it would also help if you can add your markup.
What you can do is(for now since your question and your code seems pretty vague)
$(document).ready(function() {
$("#userBase .confirm").on("click",function() {
var conBox = confirm("Are you sure ?");
var userLogin = "sampleOnly" //maybe somewhere in your html you have this
var url = "mycontroller/delete/"+userLogin //A rough guess for now
if(conBox){
$.post(url+userLogin,function(e){
var tr = $(this).closest('tr');
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();
})
});
} else {
$(this).dialog("close");
}
});
});
If you want to send data using jQuery, I'd suggest using AJAX with REST. Here's how I'd do it:
#RequestMapping(value="delete.json", method=RequestMethod.DELETE, produces="application/json")
#ResponseBody
public Boolean deleteAjaxMultiple(#RequestBody String[] gotten)
{
for (String login : gotten)
userService.remove(userService.findByLogin(login));
return true;
}
This controller handles JSON requests, in this case an array of logins. Then you'll just have to call it from JavaScript like this:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: '/delete.json', //or whatever url works for you
type: 'DELETE',
data: JSON.stringify(arr), //arr is an array of logins you want to delete
success: function(data) {
location.reload(true); //or do whatever you want on success
}
});
You need to set up Jackson for this. For more info see this and this.

Categories