gpt4 book ai didi

java - getServletContext.getRealPath() 不工作?

转载 作者:行者123 更新时间:2023-11-29 05:33:34 24 4
gpt4 key购买 nike

getServletContext.getRealPath("string") 抛出空指针异常。我如何使用它来获取真实路径?

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{

String fileName="xyz.pdf";
ServletOutputStream stream=null;
BufferedInputStream buf=null;
try
{

stream=res.getOutputStream();
String s1=getServletContext().getRealPath("pdfFiles/xyz.pdf");
File doc=new File(s1);
res.setContentType("application/pdf");
res.setHeader("Content-Disposition","attachment;filename="+fileName);
res.setContentLength((int)doc.length());
FileInputStream input=new FileInputStream(doc);
buf=new BufferedInputStream(input);
int readBytes=0;

while((readBytes=buf.read())!=-1)
stream.write(readBytes);

}
catch(Exception e){}

}

最佳答案

您已经覆盖了 GenericServlet.init(ServletContext context) 但您还没有从其中调用 super(context);。所以当你调用 GenericServlet.getServletContext() 时,它不知道上下文在哪里,所以它返回 null。

注意您的 readBytes 变量命名错误。它将包含一个字节。

关于java - getServletContext.getRealPath() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20277435/

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