问题描述
- Servlet类加载文件读取资源
-
type Exception reportmessage
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
com.itheima.Service.methdo2(Service.java:10)
com.itheima.Demo8Servlet.doGet(Demo8Servlet.java:21)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)note The full stack trace of the root cause is available in the Apache Tomcat/6.0.36 logs.
源码:package com.itheima;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class Service {
public void methdo2() throws FileNotFoundException,IOException{
Properties prop = new Properties();
prop.load(new FileReader(Service.class.getClassLoader().getResource("config.properties").getPath()));
System.out.println(prop.getProperty("username"));
System.out.println(prop.getProperty("password"));}
}
package com.itheima;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class Demo8Servlet extends HttpServlet {
/** * */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Service service = new Service(); service.methdo2(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
}
解决方案
看看到吗
com.itheima.Service.methdo2(Service.java:10) 这第10行是什么,打断点看一下。
解决方案二:
prop.load(new FileReader(Service.class.getClassLoader().getResource("config.properties").getPath()));//”config.properties“路径问题