I want to delete files after a click on an HTML link in a jsp
page.
The following is my jsp
code:
<%
File f=new File("c:\\Folder\\1.jpg");
f.delete();
%>
What href
should I use in the HTML code?
<a href......>Delete me </a>
I want to delete files after a click on an HTML link in a jsp
page.
The following is my jsp
code:
<%
File f=new File("c:\\Folder\\1.jpg");
f.delete();
%>
What href
should I use in the HTML code?
<a href......>Delete me </a>
Html
plays on client side and Java(Jsp)
plays on server side.You need to make a server request
for that.
And one more point
File f=new File("c:\\Folder\\1.jpg");
After you made the request
the above line tries to remove the file from the server
not from the user machine(who clicked the link).
You might misunderstand that jsp
and html
existed on same document. Yes but JSP
part compiles on server side itself and JSP output resolves as html and is sent to the client
.
Note:Html and Javascript cannot have access to files on the machine due to security reason.
For this you can use j query to delete without refreshing Here is the code lets have a try
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(e) {
$( "#deletefilesAnchor" ).click(function(e) {
e.preventDefault();
if (confirm('Are you sure you want to Delete Files?')) {
// Save it!
$.ajax({
type: "POST",
url: "action.jsp",
success: function(msg){
alert(msg)
},
});
} else {
// Do nothing!
}
});
});
</script>
</head>
<body>
<a id="deletefilesAnchor" href="#">Delete files</a>
</body>
</html>
action.jsp
<%
File f=new File("c:\\Folder\\1.jpg");
if(f.delete())
out.println("Sucessfully deleted file");
else
out.println("Error in deleting file");
%>
if(request.getParameter("btnSubmit")!=null) //btnSubmit is the name of your button, not id of that button.
{
File f=new File("c:\\Folder\\1.jpg");
f.delete();
}
<input type="submit" id="btnSubmit" name="btnSubmit" value="delete"/>
This you you can achieve
You can't do that like this way.
servlet/jsp is run on the server side, but the html link is run on the client side(the browser). If you see the source code of the page(click the right button of the mouse over the browser page), then you can see the jsp code is not exist.
If you want to do that, your should link to another page(like b.jsp), then in the jsp, use the the code above to delete the file.