Java Web-File download getResourceAsStream() returns NULL solution

tags: # JAVA  Java Web  document dowload

Problem Description

Critical: Servlet.service() for servlet [club.zstuca.demo.DownloadDemo] in context with path [/DEMOWeb] threw exception
java.lang.NullPointerException
	at club.zstuca.demo.DownloadDemo.doGet(DownloadDemo.java:48)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Unknown Source)

problem analysis

The file is not in the root directory of the WebAPP, causing the resource to be found.

API

Class.getResourceAsStream(String path)

JDK sets up such rules, which is well understood. When path does not start with "/", we can get the same resource file as the path where the current class is located, and when it starts with "/", we can get any path under the root of classPath. resource of.

When the path does not start with "/", the default is to obtain resources from the package where the current class is located

When the path starts with "/", resources are obtained from the project's classPath root

ClassLoader.getResourceAsStream(String path)

The default is to get from the root of the classpath,path cannot start with "/", Path refers to the loading range of the class loader. In the process of resource loading, it is loaded in the form of step-by-step delegation. "/" means the loading range in Boot ClassLoader, because this class loader is implemented in C++, So the loading range is null.

ServletContext.getResourceAsStream(String path)

By default, resources are fetched from the root directory of WebAPP. It doesn't matter whether the path under Tomcat starts with "/", of course this is related to the specific container implementation.

solution

1. Create a res folder in the root directory of WebAPP and move resources into this folder

2. Modify the code

Source code

package club.zstuca.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadDemo
 */
@WebServlet("/DownloadDemo")
public class DownloadDemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadDemo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		//response.setContentType("application/octet-stream");
		response.addHeader("content-Type", "application/octet-stream" );
		String filename = request.getParameter("filename");
		response.addHeader("content-Disposition", "attachment; filename=" + filename);
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		InputStream in = this.getServletContext().getResourceAsStream("/res/" + filename);
		
		System.out.println("res/" + filename);
		System.out.println(in);
		ServletOutputStream out = response.getOutputStream();
		byte[] bs = new byte[1024];
		int len = -1;
		while((len=in.read(bs))!=-1) {
			out.write(bs,0,len);
			
		}
		out.close();	
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Reference article

Intelligent Recommendation

getResourceAsStream() does not get the configuration file in the web project

Problem: Using Object.class.getResourceAsStream() can't get the configuration file in the web project. The simple java application test can be used, and the null pointer is reported in the web project...

GetResourceAsStream () gets the reason for the configuration file in the Web project

Today, when you write a project, you will use getresourceas.Stream() Reasons for obtaining configuring files in a web project First release the resolved code: Just through class loading to load files,...

DAO factory design and implementation class.getClassLoader (). GetResourceAsStream () is null solution

To avoid coupling code, DAO layer using the factory pattern is achieved. 1. Write a profile daoconfig.properties, here is my own employee of a table 2.DAO Interface: Define methods 3.DAO JDBC interfac...

javaWeb project class.getClassLoader().getResourceAsStream gets the result as null solution

When learning a Web project, I encountered a simple problem and recorded the solution. I am taking a Java course from Dark Horse Programmer. The course was taken in May 2018. The current IDEA is a lit...

getLastKnownLocation() returns a null solution

always uses the LocationManager.getLastKnownLocation("gps") to get the gps location. Baidu checked a lot of information on the Internet and found that this problem appeared in version 2.0 or...

More Recommendation

TelephonyManager.getDeviceId () Returns NULL Solution

TelephonyManager.getDeviceId () Returns NULL Solution In Android Development Discovery TelephonyManager.getDeviceId () Gets the return value in the case of permission is also NULL, the solution is as ...

Java uses getResource and getResourceAsStream to get the path of the file

Java uses getResource and getResourceAsStream to get the path of the file is based on the following project: the src directory is set to source root and the resources directory is set to resources roo...

getResource and getResourceAsStream take the value null; java music loop play

I wanted to implement music loop playback in a java application, but the return value of getResource("music/bg.wav") is null. I guess the path is a problem. I tried tryResource("/music/...

Java web download file

The project needs to implement the file download function on the mobile phone web terminal. Although the <a> tag and the path can also be used to achieve this function, it is obviously unsafe to...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top