首页 新闻 会员 周边

为什么servletConfig会未被初始化

0
悬赏园豆:5 [已关闭问题] 关闭于 2016-01-04 11:26

我在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>");
    }

}

胖胖的半山兄的主页 胖胖的半山兄 | 菜鸟二级 | 园豆:240
提问于:2016-01-04 11:21
< >
分享
所有回答(1)
0

你继承了httpservlet,理论上就不用再自己弄servletconfig这个类的处理了.因为父类genericservlet已经写好了init(ServletConfig config).我们自己的servlet只需要getServlet()就好了.另外.你的init方法里传入了servletconfig对象,但是并没有使用它给自己的成员变量赋值,而是调用了父类的getServletConfig方法来赋值.这个时候你覆盖了父类的方法,所有父类的config也是空了.继而你自己的成员变量config也就付不了值了.所以就空了 啊

gaoxuechaochao | 园豆:188 (初学一级) | 2018-04-21 22:29
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册