前言
ServletConfig对象
和ServletContext对象
学习笔记
添加配置
- 在web.xml文件中,以键值对的形式添加配置参数,可以添加多组
<<name>>
:参数名(键)
<<value>
:参数值(值)
1 2 3 4
| <init-param> <param-name><<name>></param-name> <param-value><<value>></param-value> </init-param>
|
获取Servlet初始化参数对象
1
| ServletConfig config = this.getServletConfig();
|
读取参数
通过键读取值
1
| config.getInitParameter("<<name>>");
|
读取所有的键
1 2 3 4
| Enumeration<String> names = config.InitParameterNames(); while(names.hasMoreElements()) { String name = names.nextElement(); }
|
设置字符集
1
| req.setCharacterEncoding("utf-8");
|
获取ServletContext对象
1 2 3
| ServletContext context = this.getServletContext(); ServletContext context = req.getServletContext(); ServletContext context = this.getServletConfig().getServletContext();
|
获取资源名
获取资源位置
1
| context.getReadPath(getServletName());
|
写入Context数据
- 保存需要长久保存的数据(只要不关闭服务器就可以一直保存)
<key>
:数据名(键)
<value>
:数据值(值)
1
| context.setAttribute("<key>", "<value>");
|
读取Context数据
1
| context.getAttribute("<key>", "<value>");
|
参考文献
达内教育