在Java Web项目中获取路径,建立一个servlet在doPost()方法中添加如下代码获取,不能通过浏览器中输入URL地址调用:
package com.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletSample extends HttpServlet {
private static final long serialVersionUID = 416863504806100479L;
/**
* POST方式
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String realPath = req.getSession().getServletContext().getRealPath("/");
System.out.println(realPath);
}
}