从servlet访问WebContent中的文件

Thi*_*amy 4 java servlets vs-web-application-project servlet-3.0 jsoup

我尝试使用servlet的相对路径访问WebContent/alerts文件夹中的html文件.但我无法使用其相对路径访问它,

在此输入图像描述

使用相对路径从Servlet访问WebContent内的文件:

protected Element getSummary(String value) throws IOException
{
    Element element=null;
    Summary summary = Summary.valueOf(value);
    switch(summary) {
    case rtp_summary:
        element=parseDIV(new File("../../WebContent/alerts/rtp_bcklg_mail.html"),"rtp_summary");
        break;
    case ffu_summary:
        element=parseDIV(new File("/../../WebContent/alerts/ffu_comp_bcklg_mail.html"),"ffu_summary");
        break;    
    default:
        System.out.println("Enter a valid choice");
        break;
    }
    return element;
}
Run Code Online (Sandbox Code Playgroud)

使用相对路径从Java Thread访问WebContent内的文件:

 public class WriteJSONFile implements Runnable{

WriteJSONFile(){
}

@Override

public void run()
{
    try {
        createJSONFile();
    } catch (IOException e) {

        e.printStackTrace();
    }
}

@SuppressWarnings("unchecked")
private static void createJSONFile() throws IOException
{
    String path="C:/Users/Thiru/Documents/Website Design/Macaw/";
    JSONArray jsonArray=new JSONArray();
    JSONObject rtpStatus=new JSONObject();
    rtpStatus.put("name","RTP");
    rtpStatus.put("status",parseDIV(new File(path+"WebContent/alerts/rtp_bcklg_mail.html"),"rtp_health"));
    jsonArray.add(rtpStatus);

    JSONObject proposalattribStatus=new JSONObject();
    proposalattribStatus.put("name","PROPOSAL ATTRIBUTE");
    proposalattribStatus.put("status",parseDIV(new File(path+"WebContent/alerts/prpsl_txtsrch.html"),"prpsl_attrb_health"));
    jsonArray.add(proposalattribStatus);

    writetoFile(jsonArray);
}


private static void writetoFile(JSONArray jsonArray) {
    try {
        String path="C:/Users/Thiru/Documents/Website Design/Macaw/";
        FileWriter file = new FileWriter(path+"WebContent/properties/status.json");
        file.write(jsonArray.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }   
}

protected static String parseDIV(File input, String divElement)
        throws IOException {
    Document doc = Jsoup.parse(input, "UTF-8");
    String content = doc.getElementById(divElement).val();
    System.out.println(divElement +" "+content);
    return content;
}
Run Code Online (Sandbox Code Playgroud)

}

我还想使用相对路径从RESTful web服务方法访问Webcontent中的文件.提前致谢.

dna*_*ult 7

使用ServletContext.getRealPath()在磁盘上找到该文件.请注意,这仅在部署期间webapp"爆炸"时才有效.

例如:

   File f = new File(getServletContext().getRealPath("alerts/rtp_bcklg_mail.html"));
Run Code Online (Sandbox Code Playgroud)