gpt4 book ai didi

java - 从 servlet 访问 WebContent 中的文件

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:35 25 4
gpt4 key购买 nike

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

enter image description here

使用相对路径从 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;
}

使用相对路径从 Java 线程 访问 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;
}

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

最佳答案

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

例如:

   File f = new File(getServletContext().getRealPath("alerts/rtp_bcklg_mail.html"));

关于java - 从 servlet 访问 WebContent 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21415413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com