Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsp : delete file when click on html link

Tags:

java

jsp

servlets

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>
like image 925
user2651739 Avatar asked Feb 03 '26 17:02

user2651739


2 Answers

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.

like image 141
Suresh Atta Avatar answered Feb 06 '26 05:02

Suresh Atta


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");
%>