0

When I run :

Enumeration<String> enums = this.getServletConfig().getInitParameterNames();

I get the HTTP Status 500 error in my broswer.

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NullPointerException com.ypd.config.ConfigDemo.doGet(ConfigDemo.java:32) javax.servlet.http.HttpServlet.service(HttpServlet.java:622) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

note The full stack trace of the root cause is available in the Apache Tomcat/9.0.0.M17 logs. Apache Tomcat/9.0.0.M17

The snapshot:

enter image description here

My config code in web.xml:

<servlet>
    <servlet-name>ConfigDemo</servlet-name>
    <servlet-class>com.ypd.config.ConfigDemo</servlet-class>
    <init-param>
        <param-name>path</param-name>
        <param-value>/Users/luowensheng/Downloads/图片1.png</param-value>
    </init-param>
    <init-param>
        <param-name>aaa</param-name>
        <param-value>aaa's value</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>ConfigDemo</servlet-name>
    <url-pattern>/configDemo</url-pattern>
</servlet-mapping>

And in my ConfigDemo.java:

public class ConfigDemo extends HttpServlet{

    private ServletConfig config;

    @Override
    public void init(ServletConfig config) throws ServletException {

        this.config = config;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Enumeration<String> enums = this.getServletConfig().getInitParameterNames(); // this is 32th line, here I get the error.
        while(enums.hasMoreElements()) {
            String paramName = enums.nextElement();
            String paramValue = this.getServletConfig().getInitParameter(paramName);

            resp.getWriter().write(paramName + "=" + paramValue);

        }

    }
}

But in the end I found if I annotation the below code, there will not have the error:

private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException {

    this.config = config;
}

Why? why can not have this ServletConfig member variable here?

aircraft
  • 25,146
  • 28
  • 91
  • 166

0 Answers0