getServlet上下文.getRealPath()不工作



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变量命名错误。它将包含一个字节。

你可以试试这个:

String s1= req.getSession().getServletContext().getRealPath("pdfFiles/xyz.pdf");  

如果服务器是Websphere,请执行以下操作:

->打开管理控制台
->应用程序->websphere企业应用程序
->选择已部署的项目(确保已停止)
->选择"类加载和更新检测"
->在WAR类加载器策略中,选择"应用程序的单个类加载器"
->启动应用程序

完成。

最新更新