首先需要强调的是,a标签无法打开本地文件链接(具体为无反应,无跳转)。
于是换个思路:由于java程序可以打开本地文件,于是我们可以从网页获取本地文件链接,并将其传到java程序中,然后通过该程序打开本地文件。
jsp代码如下:
<%--a标签不能打开本地文件链接,需要通过java程序来实现打开本地文件的操作--%>
<form action="openFileUrl">
<input type="text" name="fileUrl" value="${url}" hidden id="fileUrl">
<a οnclick="fileUrlClick()">${url}</a>
<input type="submit" hidden id="submitFileUrl">
</form>
javascript代码如下:
function fileUrlClick(){
var submitFileUrl=document.getElementById("submitFileUrl")
submitFileUrl.click();
}
java代码如下:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//a标签不能打开本地文件链接,需要通过java程序来实现打开本地文件的操作
@WebServlet("/openFileUrl")
public class openFileUrlServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fileUrl = req.getParameter("fileUrl");
File file = new File(fileUrl); // 本地文件路径
URL url = file.toURI().toURL(); // 转换为URL对象
System.out.println(url);
Desktop desktop = Desktop.getDesktop(); // 获取桌面对象
desktop.open(new File(url.getFile())); // 打开本地文件
}
}
解释一下,js的作用是实现点击链接后,自动提交文本框的内容到java程序中。