下载 servlet 的 doGet() 抛出 NullPointerException
我正在开发一个简单的 Web 应用程序,客户端应该能够通过单击 HTML 页面中的超链接来下载 pdf 文件。我正在使用 MVC 模式。下面是我的 Servlet 代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/pdf");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/abc.pdf");
int read = 0;
byte [] bytes = new byte[1024];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes)) != -1)
{
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
我正在使用 Apache Tomcat 6.0< /strong>
下面是我收到的错误:
SEVERE: Servlet.service() for servlet download threw exception
java.lang.NullPointerException
at BookDownloaderServlet.doGet(BookDownloaderServlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
abc.pdf 正确放置在应用程序上下文下 。仍然找不到此异常的原因。 请帮忙。 提前致谢
I am developing a simple web application in which client should be able to download a pdf file by clicking a hyperlink from the HTML page.I am using MVC pattern.Below is my code for Servlet :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/pdf");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/abc.pdf");
int read = 0;
byte [] bytes = new byte[1024];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes)) != -1)
{
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
I am using Apache Tomcat 6.0
Below is the error i am getting :
SEVERE: Servlet.service() for servlet download threw exception
java.lang.NullPointerException
at BookDownloaderServlet.doGet(BookDownloaderServlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
abc.pdf is correctly placed under application contex . Still cant find a reason for this exception.
kindly help.
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这行很可能是您的问题:
is
被分配给null
。它在这里抛出一个异常:看起来 CLASSPATH 的根目录中不存在
abc.pdf
文件。Most likely this line is your problem:
is
is assigned tonull
. It throws an exception here:Looks like
abc.pdf
file does not exist in the root of your CLASSPATH.尝试将
InputStream is = ctx.getResourceAsStream("/abc.pdf");
更改为InputStream is = ctx.getResourceAsStream("abc.pdf");
删除
/
try changing
InputStream is = ctx.getResourceAsStream("/abc.pdf");
toInputStream is = ctx.getResourceAsStream("abc.pdf");
remove
/