getRealPath()和getContextPath()的区别

   在程序中常常要获取文件的路径,有的时候需要用到相对路径而有的时候就要用到绝对路径,一提到绝对路径大家一定想到了getRealPath()但是这个方法已经不推荐使用了,但是我们还必须要得到绝对路径怎么办呢?不用急,用这个:

request.getSession().getServletContext().getRealPath("/")+"userinfo.properties"; 

 

这样以来在使用文件的时候就会得到绝对的路径,下面是运行后的效果:

E:\tomcat\webapps\myajax\userinfo.properties 

 

得到相对路径就用:

 

request.getContestPath()

 

运行后的效果为:

 

/myajax/userinfo.properties

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java Web 图片上传回显的 JSP 和 Servlet 完整代码示例。 JSP 页面代码(upload.jsp): ```jsp <!DOCTYPE html> <html> <head> <title>图片上传回显</title> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="上传"> </form> <% if (request.getAttribute("imageUrl") != null) { %> <img src="<%= request.getAttribute("imageUrl") %>"> <% } %> </body> </html> ``` Servlet 代码(UploadServlet.java): ```java import java.io.File; import java.io.IOException; import java.util.UUID; 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 javax.servlet.http.Part; @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String UPLOAD_DIR = "uploads"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String applicationPath = request.getServletContext().getRealPath(""); String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; File fileSaveDir = new File(uploadFilePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdirs(); } Part part = request.getPart("image"); String fileName = UUID.randomUUID().toString() + "_" + part.getSubmittedFileName(); String filePath = uploadFilePath + File.separator + fileName; part.write(filePath); String imageUrl = request.getContextPath() + "/" + UPLOAD_DIR + "/" + fileName; request.setAttribute("imageUrl", imageUrl); request.getRequestDispatcher("upload.jsp").forward(request, response); } } ``` 注意事项: - 在 JSP 中,当检查请求属性 "imageUrl" 是否存在时,请使用 `request.getAttribute("imageUrl") != null`。 - 在 Servlet 中,将上传的文件保存到服务器上的路径可以使用 `request.getServletContext().getRealPath("")` 获取当前应用程序的根目录。 - 在 Servlet 中,获取上传的文件的文件名可以使用 `part.getSubmittedFileName()` 方法。 - 在 Servlet 中,通过 `request.getContextPath()` 获取应用程序的上下文路径,例如 "/myapp"。 - 在 Servlet 中,使用 `request.getRequestDispatcher("upload.jsp").forward(request, response)` 转发回 JSP 页面,并在 JSP 页面中显示上传的图片。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值