jQuery+Spring remove from database - java

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.

Related

JSP Multiple Buttons with Different API in Single Form

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');
}
});
}

MVC Spring Controller, display dbData in HTML file

If I write a Spring MVC Controller, how can I display the DBData in my HTML file.
e.g. I have db.table called Setting and I want to display the IDs from that table in my HTML file as a Dropdown list.
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
public #ResponseBody Setting getId() {
return this.setting;
}
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<option value="0" ><%=setting[ID]%></option>
</select>
</td>
</tr>
</table>
Well it depends on how you retrieve data... do you use AJAX calls? Or do you need them when page is loaded?
Let's see the 2 scenarios
Note: in boths scenarios we assume you are returning a list of object like this:
public class Option{
private String value;
private String text;
//getter and setter
}
AJAX CALL: for this I assume we are using JQuery; in this case you will have in your JS or JSP file something like this:
$.ajax({
url : 'customchannel',
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
type : 'GET',
success : function(items) {
$.each(items, function (i, item) {
$('#selectReportChannel').append($('<option>', {
value: item.value,
text : item.text
}));
});
},
error : function(data) {
}
});
<select id="selectReportChannel" class="form-control">
</select>
Page loaded In this case in your controller who will render the HTML page you can do something like this:
#Controller
public class CustomChannelController {
private Setting setting;
private Diagram diagram;
private Channel channel;
#RequestMapping(value = "/customchannel", method = RequestMethod.GET)
public ModelAndView getId(Model uiModel) {
uiModel.add("options", this.setting);
return new ModelAndView("yourPage", uiModel) ;
}
Then in the HTML page you can use JSTL in this way:
<table>
<tr>
<td>
<label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
</td>
<td>
<select id="selectReportChannel" class="form-control">
<c:forEach items="${options}" var="option">
<option value="${option.value}">${option.text}</option>
</c:forEach>
</select>
</td>
</tr>
</table>
Ok, I have found a solution. First a need to create a Spring MVC Controller then a Service and link then the Controller to the Backbone model file.

Ajax success don't execute

I'm doing a login page with Spring MVC in server and JS & Ajax in client. I don't know what's wrong, the code of the server executes but don't return nothing.
login.html
<script type="text/javascript">
$(function() {
$(".loguser").click(function() {
var user = $("#login").val();
var pass = $("#pass").val();
$.ajax({
method: "POST",
url : "${prefix}loginUser",
data : "username=" + user + "&password=" + pass,
dataType : "json",
success: function(data){
if (data.res == "YES") alert("ok");
else alert("NOPE");
}
});
})
})
</script>
<table id="userData" class="center">
<tr id="usernametr">
<th><label for="user">Nombre de usuario: </label></th>
<th><input id="login" type="text" name="login" value=""
placeholder="Name" required /></th>
</tr>
<tr>
<th><br /></th>
</tr>
<tr>
<th><label for="pass">Clave de usuario: </label></th>
<th><input id="pass" type="password" name="pass" value=""
placeholder="Password" required /></th>
</tr>
<tr>
<th><button class="loguser">Acceder</button></th>
<th><input type="button" name="lost"
value="He perdido mi clave" /></th>
</tr>
</table>
HomeController.java:
#RequestMapping(value = "/loginUser")
#ResponseBody
#Transactional
public String loginUser(#RequestParam("username") String username,
#RequestParam("password") String pass, HttpServletRequest request, Model model) {
logger.info("Trying to log in {} {}", username, pass);
if (username.length() > 3) {
logger.info("ok");
return new String("[\"res\": \"YES\"]");
} else {
logger.warn("nope");
return new String("[\"res\": \"NOPE\"]");
}
}
I tryiend returning EntityResponse too but nothing change. Springs console prints the logger info or warn but Firefox's javascript console doesnt.
You must specify Requestmethod in controller like
#RequestMapping(value = "/loginUser", method = RequestMethod.POST)
You must Return Json Values In { }
Braces

input type file goes blank when submit form onchange

Hi i am uploading a file using <input type="file"> in spring mvc. I submit form on change event of file and show uploaded process. But file content not uploaded and get null on server. If i upload on click of submit button every thing works fine. This is my code:
Html File:
<form:form method="POST" modelAttribute="book" id="saveBook"
name="saveBook" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Book :</td>
<td> </td>
<td>
<input type="file" name="file" id="file" class="edit_form" onchange="return upload('<c:url value='/bookstore/librery/uploadBook' />', 'saveBook', this);" />
<form:errors path="file" />
</td>
</tr>
</table>
</form:form>
Jquery Code:
function upload(requestUrl, formId, clickedObj) {
if (clickedObj && eval(clickedObj) && clickedObj != null && clickedObj != undefined) {
clickedObj.disabled = true;
}
var formData = new FormData(document.getElementById(formId));
$.ajax({
'url': requestUrl,
'type': 'POST',
'data': formData,
'cache': false,
'contentType': false,
'processData': false,
success: function (data) {
$("#tempLoc").val(data.tempLoc);
$("#bookPreview").attr("src", "data:image/png;base64," + data.image);
$("#image").val(data.image);
clickedObj.disabled = false;
},
error: function (xhr, status, err) {
clickedObj.disabled = false;
var tempErrorHTML = getAjaxRequestErrorMsg(xhr);
alert(tempErrorHTML);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
//Do something with upload progress
alert('percentComplete = ' + percentComplete + '%');
}
}, false);
return xhr;
},
}, 'json');
}
If i call upload function on click of submit button every thing works fine. I think form is submitted before file uploaded but don't know how to make things correct.
I can't use submit function because I need to show upload progressbar. Please help.
Thanks In Advance.

Refreshing the table columns in jsp page on click of refresh button at each row using ajax/javascript

Hi I have a JSP page as below,jsp page contains one table in which i am displaying data by iterating through the list from the action class.
each row of a table has refresh button at row level.jsp is as shown below.
<script type="text/javascript">
function refreshRecord(id)
{
$(document).ready(function(){
var fileId=id;
alert(fileId);
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data: {fileId:fileId},
success:function(data){
alert("returned from action");
}
});
});
}
</script>
</head>
<body>
<%#include file="index1.html" %>
<div class="box2">
<div class="box3">
<s:property value="userId"/>
</div>
<center><h2>FILE STATUS</h2></center>
<center>
<form action="Upload" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Upload your file:</label>
<input type="hidden" name="upload" value="upload"/>
<input type="file" name="myFile" size="40" class="file"/>
<input type="submit" value="Upload" class="button"/>
<input type="submit" value="Refresh" class="button"/>
</form>
</center>
<center>
<table border="1" class="displaytab" id="rtable">
<s:if test="%{user.roles == 'admin'}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center>Admin</center></td></tr>
</s:if>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="uploadList" var="m">
<tr>
<td><s:property value="%{#m.fileId}" /></td>
<td><s:property value="%{#m.fileName}" /></td>
<td><s:property value="%{#m.uploadDate}" /></td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><s:property value="%{#m.status}" /></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"> </td>
<td><img src="images/refresh.png" title="Refresh" onclick="refreshRecord(<s:property value="%{#m.fileId}" />);"></td>
</tr>
</s:iterator>
</table>
</center>
at the refresh button onclick i am calling onclick="refreshRecord();"> this javascript method it will go to action class get the latest values of status and # records.
through ajax i am passing this fileId to action class checkStatusAndNumRecsAction.java to get the updated status and #records column values from database
my action class is as below
import com.mxui.db.api.PersistenceService;
import com.mxui.db.service.*;
import com.opensymphony.xwork2.ActionSupport;
public class checkStatusAndNumRecsAction extends ActionSupport
{
/**
*
*/
private static final long serialVersionUID = 6450400234448854648L;
private String status;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
private long numRecords;
public long getNumRecords()
{
return numRecords;
}
public void setNumRecords(long numRecords)
{
this.numRecords= numRecords;
}
private String fileId;
public String getFileId()
{
return fileId;
}
public void setFileId(String fileId)
{
this.fileId = fileId;
}
public String execute()
{
PersistenceService svc = PersistenceServiceImpl.getInstance();
status = svc.getStatusByFileId(fileId);
System.out.println("status is "+status);
numRecords = svc.getNumRecordsByFileId(fileId);
System.out.println("num records are "+numRecords);
return "SUCCESS";
}
}
this action get the values of status and #records from database
what i want to do is i should get the values of status and numRecords from action class to jsp using ajax and replace the tables of status and #records column with the new retrieved data from action class.on click of that row refresh button.
In the function defined in success: you will need to write javascript that replaces the contents of the <TD> for the record that has been refreshed. You can identify the <TD> by using the fileId. For example: <td id="%{#m.fileId}"><s:property value="%{#m.status}" /></td> and using jQuery search for this fileId and by using replaceWith substitute the new value of status. For example: $("td#fileId").replaceWith(newStatusData);
Depending of the format of the data returned to the AJAX call you might need to do some parsing in order to extract the data that you want.
EDIT: Just seen your comment. Can you control to format of the data returned to the AJAX call? If so you might like to format in JSON. Although a simple CSV format would be sufficient. Also can you post an example of the data sent back to the AJAX.
You appear to be missing a servlet that recuperates the values from the DB and sends then to the client. In your servlets doPost() method you need to call the methods that return the status of the record and number of records and return them to the client. I imagine servlet code something like this:
#WebServlet(checkStatusAndNumRecs)
class MyServlet extends HttpServlet
protected doPost(HttpServletRequest request, HttpServletResponse)
throws IOException, ServletException{
String fileId = request.getParameter("fileId");
String status = XXXXX.getStatus(fileId);
String numRec = XXXXX.getNumRecords();
String responseTxt = status + "," + numRec;
response.out.println(responseTxt);
response.getWriter().println(responseTxt);
}
XXXXX is the object that encapsulates the calls to the DB to retrieve the values of status and record number.
And also you need to change to jQuery AJAX to something like this:
$.ajax({
type: "post",
url: "checkStatusAndNumRecs",
data: "fileId=" + fileId,
success: function(data){
var rData = data.split(",");
$("td#fileId").replaceWith(rData[0]);
// Do the same for the record number data: rData[1]
}

Categories