HTTP状态 500 - 内部服务器错误com.xurong.servletOther.ServletConfigureDemo.doGet
# HTTP状态 500 - 内部服务器错误com.xurong.servletOther.ServletConfigureDemo.doGet(ServletConfigureDemo.java:33)
1.原来是想实现一个servlet配置信息的访问,其源码如下:
1.java代码:
package com.servletOther;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @auther xu
* @date 2022/4/3 - 15:31
*/
public class ServletConfigureDemo extends HttpServlet {
private ServletConfig config;
public ServletConfigureDemo() {
super();
}
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取配置文件方式1:
// String encodingValue = config.getInitParameter("encoding");
// System.out.println(encodingValue);
//获取配置文件方式2:
String encodingValue = super.getServletConfig().getInitParameter("encoding");
System.out.println(encodingValue);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
2.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>servletConfig</servlet-name>
<servlet-class>com.servletOther.ServletConfigureDemo</servlet-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>servletConfig</servlet-name>
<url-pattern>/servletConf1</url-pattern>
</servlet-mapping>
</web-app>
将该servlet程序部署到Tomcat服务器上,通过客户端url访问,报如上500错误。
2.解决:
3.原因
super.getServletConfig()就是调用GenericServlet类中的getServletConfig()方法:如下
由此可知,super.getServletConfig()返回值时null,null.getInitParameter("encoding");由此引发一个空指针异常
4.深层次探究
为什么要引入父类的init(config),很自然的想到哪一个父类中有带ServletConfig类型的方法:
由该继承关系可知,DenericServlet类中实现了init(ServletConfig)方法,点进去看一下:
由此可知,
1.过程:
通过在重写init(ServletConfig config)方法中引入super.init(ServletConfig config),也就是GenericServlet类中的init(ServletConfig config),该方法实现了Servlet接口中的抽象方法int(ServletConfig config),通过GenericServlet类中的init(ServletConfig config)完成对config赋值的操作