Servlet获取当前服务器的实际路径

Servlet/Jsp需要操作服务器所拥有的资源,为此需要得到其绝对路径或实际路径,

在Servlet的doGet方法中加入以下代码可以查看服务器的实际路径。

 1 package com.mhb;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletContext;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 public class getRealPathServletDemo extends HttpServlet {
13 
14     public void init() throws ServletException {
15     }
16 
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19         response.setContentType("text/html;charset=utf-8");
20         ServletContext context = this.getServletContext();
21         PrintWriter out = response.getWriter();
22         out.print("当前服务器的实际路径为:"+context.getRealPath(""));
23     }
24 
25     public void doPost(HttpServletRequest request, HttpServletResponse response)
26             throws ServletException, IOException {
27     }
28 
29     public void destroy() {
30         super.destroy(); 
31     }
32 }
原文地址:https://www.cnblogs.com/tdcqma/p/4757215.html