简体   繁体   中英

getServletContext.getRealPath() is not working?

getServletContext.getRealPath("string") is throwing a null pointer exception. How can I use it to get the real path?

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){}

}

You've overridden GenericServlet.init(ServletContext context) but you haven't called super(context); from within it. So when you call GenericServlet.getServletContext(), it doesn't know where the context is, so it returns null.

NB your readBytes variable is misnamed. It will contain a single byte.

你可以试试这个:

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

If the server is Websphere, do the following:

->open admin console
->applications->websphere enterprise applications
-> select your deployed project (make sure its stopped)
->select 'class loading and update detection'
->in the WAR class loader policy, select 'single class loader for application'
->start the application

done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM