我在init()里面已经将servletConfig赋值了,为什么还会报500错误,排查了发现是servletConfig空指针异常
代码如下:
package test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/HelloWorld") public class HelloWorld extends HttpServlet { private static final long serialVersionUID = 1L; private transient ServletConfig servletConfig ; public void init(ServletConfig config) throws ServletException { servletConfig =this.getServletConfig(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String servletName = servletConfig.getServletName(); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.print("<html><head></head><body>hello "+servletName+"</body></html>"); } }
你继承了httpservlet,理论上就不用再自己弄servletconfig这个类的处理了.因为父类genericservlet已经写好了init(ServletConfig config).我们自己的servlet只需要getServlet()就好了.另外.你的init方法里传入了servletconfig对象,但是并没有使用它给自己的成员变量赋值,而是调用了父类的getServletConfig方法来赋值.这个时候你覆盖了父类的方法,所有父类的config也是空了.继而你自己的成员变量config也就付不了值了.所以就空了 啊