ServletConfig 对象

容器初始化 Servlet 时,会创建一个 ServletConfig 对象,可获得当前 Servlet 的初始化参数信息。

获得 ServletConfig 对象

直接从带参的 init() 方法中提取

1
2
3
4
5
6
7
8
9
10
11
12
public class ServletConfigDemo extends HttpServlet {
private ServletConfig servletConfig;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取Servlet得名字
this.servletConfig.getServletName();
}
@Override
public void init(ServletConfig config) throws ServletException {
//从带参init方法中,提取ServletConfig对象
this.servletConfig = config;
}
}

调用 GenericServlet 提供的 getServletConfig() 方法获得

查看更多

ServletContext

每个Web应用仅有一个ServletContext对象(webapps 下的每个目录都是一个 Web 应用)。

Web容器启动时创建,容器关闭或应用被卸载时结束。

该对象中保存了当前应用程序相关信息,

ServletContext 对象也被称为 Context 域对象。

ServletContext的存在,就是为了存放必须的、重要的、所有用户需要共享的、线程又是安全的一些资源信息,这样不仅节省了空间,还提高了效率。

查看更多

Servlet是否需要手动关闭输出流?

参考:Servlet不用手动关闭输出流么?-CSDN社区

测试用的是tomcat7.0,resoponse如果没有关闭,tomcat会自动关闭 org.apache.catalina.core.ApplicationDispatcher.doForward(ServletRequest request, ServletResponse response)方法 最后一段代码是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Close anyway
try {
PrintWriter writer = response.getWriter();
writer.close();
} catch (IllegalStateException e) {
try {
ServletOutputStream stream = response.getOutputStream();
stream.close();
} catch (IllegalStateException f) {
// Ignore
} catch (IOException f) {
// Ignore
}
} catch (IOException e) {
// Ignore
}

可以清楚看到不管你有没有关闭,tomcat都重新关闭了一次

查看更多

配置 Servlet 初始化参数 - JavaWeb

web.xml 配置

使用一个或多个 元素为 Servlet 配置初始化参数

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" metadata-complete="false" version="4.0">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>net.biancheng.www.MyServlet</servlet-class>
<!-- Servlet 初始化参数 -->
<init-param>
<param-name>name</param-name>
<param-value>编程帮</param-value>
</init-param>
<!-- Servlet 初始化参数 -->
<init-param>
<param-name>URL</param-name>
<param-value>www.biancheng.net</param-value>
</init-param>
</servlet>
</web-app>

@WebServlet 配置

查看更多