javaweb学习总结二十四(servlet经常用到的对象)
一:ServletConfig对象
1:用来封装数据初始化参数,在服务器web.xml配置文件中可以使用<init-param>标签配置初始化参数。

2:实例演示
web.xml文件中配置初始化参数:
<servlet>
<servlet-name>ServletDemo</servlet-name>
<servlet-class>com.hlcui.servlet.ServletDemo</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>Tom</param-value>
</init-param>
<init-param>
<param-name>age</param-name>
<param-value>26</param-value>
</init-param>
<init-param>
<param-name>salary</param-name>
<param-value>12000</param-value>
</init-param>
</servlet>
servlet类中读入参数:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
// 根据参数名,获取指定属性值
String value = this.getServletConfig().getInitParameter("name");
System.out.println("value=" + value);
System.out.println("..........");
// 获取多个属性值
Enumeration e = this.getServletConfig().getInitParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value2 = this.getServletConfig().getInitParameter(name);
System.out.println(name + "=" + value2);
}
}
在web.xml中配置初始化参数,然后在创建servlet实例时调用init()方法将servletconfig对象传给servlet类。
private ServletConfig config;
public void doGet(HttpServletRequest request, HttpServletResponse response) {
String value = config.getInitParameter("name");
System.out.println(value);
}
public void init(ServletConfig config) {
this.config = config;
}
只是httpServlet的实现类GenericServlet已经帮我们做好了这些工作。
二:ServletContext对象
1:ServletContext对象代表一个web应用,多个servlet共享servletContext对象的数据
2:ServletContext对象的生命周期,当服务器启动的时候,会为服务器内的每一个web应用
创建servletContext对象,当服务器关闭的时候,会销毁servletcontext对象。


3:web应用中的多个servlet共享servletContext对象资源
示例如下:
servletDemo1将数据绑定在servletContext对象上
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//servletDemo1将数据绑定在servletContext对象上
this.getServletContext().setAttribute("name", "warrior");
}
}
ServletDemo2获取servletContext中的数据
public class ServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//ServletDemo2获取servletContext中的数据
String name = (String) this.getServletContext().getAttribute("name");
System.out.println(name);
}
}
4:服务器会将配置文件中的参数会自动封装到servletContext中,可以使用一个或者多个<context-param></context-param>标签
配置参数,context-param标签配置的参数是属于整个web应用的,而init-param标签配置的参数是属于某个servlet对象的。
示例如下:
web.xml中配置:一般情况下,可以在web.xml中配置属于context域的参数,这样所有的servlet都可以使用
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
<context-param>
<param-name>name</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>root</param-value>
</context-param>
servlet类中获取参数:
public class ServletDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取某个参数
String url = this.getServletContext().getInitParameter("url");
System.out.println(url);
System.out.println("..................");
// 获取多个参数
Enumeration e = getServletContext().getInitParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = this.getServletContext().getInitParameter(name);
System.out.println(name + "=" + value);
}
}
}
5:转发
转发:是客户端发送请求到服务器,然后启动一个servlet响应请求,如果这个servlet没有对应的资源,可以将请求转发给另一个资源,比如jsp。
就比如:A向B借钱,但是B没有,但是B说可以帮助向C借,这就是转发。
重定向:是客户端发送请求到服务器,然后启动一个servlet响应请求,这个servlet没有对应资源,它就给浏览器返回一个地址,让浏览器从新发送
请求到新的地址,就比如:A向B借钱,但是B没有,B告诉A,C有钱,让B去找C借。
转发:一次请求request 重定向:两次请求
示例如下:
public class ServletDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "hello world!";
request.setAttribute("data", data); //将数据绑定到request请求上
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/1.jsp");
rd.forward(request, response);
}
}
6:读取web中的资源文件
1):在web层读取配置文件,就是在servlet中读取配置文件
a:文件如果在src源文件下面,在doGet()方法中调用test1方法,那么可以使用servletContext对象读取配置
文件,路径为/WEB-INF/classess下面,因为servlet是读取服务器下面的文件,所以一定是class字节码文件
/**
* 当配置文件在src下面的时候
*/
private void test1() throws IOException {
// 1:读取配置文件内容
InputStream in = this.getServletContext().getResourceAsStream(
"/WEB-INF/classes/db.properties");
Properties props = new Properties();
// 2:加载配置内容到properties对象
props.load(in); String url = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println("url=" + url + "\nusername=" + username
+ "\npassword=" + password);
}
b:如果配置文件在包的下面,那么路径就要加上包名,因为在服务器中包名会被解释成目录,所以路径如下
/**
* 当配置文件在包下面的时候
*
* @throws IOException
*/
private void test2() throws IOException {
// 1:读取配置文件内容
InputStream in = this.getServletContext().getResourceAsStream(
"/WEB-INF/classes/com/hlcui/servlet/db.properties");
Properties props = new Properties();
// 2:加载配置内容到properties对象
props.load(in); String url = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println("url=" + url + "\nusername=" + username
+ "\npassword=" + password);
}
c:如果配置文件在webroot下面,那么更简单,直接/文件,/ 就代表根目录
/**
* 当配置文件在webroot下面时
* @throws IOException
*/
private void test3() throws IOException{
// 1:读取配置文件内容
InputStream in = this.getServletContext().getResourceAsStream("/db.properties");
Properties props = new Properties();
// 2:加载配置内容到properties对象
props.load(in); String url = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println("url=" + url + "\nusername=" + username
+ "\npassword=" + password);
}
2):如果想获取文件的名称,可以使用servletContext的getrealpath方法,如果配置文件路径放的位置不同,
可以参考上一步的路径
/**
* 获取文件名称并读取文件资源
*
* @throws IOException
*/
private void test4() throws IOException {
// 1:获取文件绝对路径
String path = this.getServletContext().getRealPath(
"/WEB-INF/classes/db.properties");
String filename = path.substring(path.lastIndexOf("\\"));
System.out.println("资源名称:" + filename);
InputStream in = new FileInputStream(path);
Properties props = new Properties();
// 2:加载配置内容到properties对象
props.load(in); String url = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println("url=" + url + "\nusername=" + username
+ "\npassword=" + password);
}
3):使用类加载器读取配置文件
场景:在web层(servlet类中),我们可以通过获取servletContext读取应用中的资源文件,但是如果不是在
web层,或者是为了降低web层与其他层(业务层service或者数据访问层dao)的耦合性,可以使用类加载器读取
配置文件,使用类加载器读取配置文件要求配置文件不能太大,因为类加载器首先要把配置文件加载到内存中,文件
太大会对虚拟机造成一定的压力。
public class StuDAO {
//1:在非web层读取配置文件
public void findAll() throws IOException {
InputStream in = StuDAO.class.getClassLoader().getResourceAsStream("db.properties");
Properties props = new Properties();
props.load(in);
String url = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println("url=" + url + "\nusername=" + username
+ "\npassword=" + password);
}
}
注意:这里的路径要和上面的web层做区分,web层时以web根目录为当前目录,而类加载器
读取文件是在classes目录中,而db.properties则是在classes目录中
如果我们直接在服务器上db.properties文件修改内容,则通过浏览器访问服务器时,读取的配置文件内容依然
是上一次的历史数据,因为类加载器只会加载一次,如果上一次已经加载,那么就不会再次加载,这里类加载器
的机制。要想使在服务器上面修改的内容生效,需要使用另一个API:
如下:
public void findAll() throws IOException {
URL url = StuDAO.class.getClassLoader().getResource("db.properties");
String path = url.getPath();
InputStream in = new FileInputStream(path);
Properties props = new Properties();
props.load(in);
String url2 = props.getProperty("url");
String username = props.getProperty("username");
String password = props.getProperty("password");
System.out.println("url=" + url2 + "\nusername=" + username
+ "\npassword=" + password);
}
使用getResource()是可以生效的!!!
javaweb学习总结二十四(servlet经常用到的对象)的更多相关文章
- javaweb学习总结(二十四)——jsp传统标签开发
一.标签技术的API 1.1.标签技术的API类继承关系 二.标签API简单介绍 2.1.JspTag接口 JspTag接口是所有自定义标签的父接口,它是JSP2.0中新定义的一个标记接口,没有任何属 ...
- java web学习总结(二十四) -------------------Servlet文件上传和下载的实现
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法
python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法window安装redis,下载Redis的压缩包https://git ...
- 学习笔记:CentOS7学习之二十四:expect-正则表达式-sed-cut的使用
目录 学习笔记:CentOS7学习之二十四:expect-正则表达式-sed-cut的使用 24.1 expect实现无交互登录 24.1.1 安装和使用expect 24.2 正则表达式的使用 24 ...
- 设计模式学习(二十四):Spring 中使用到的设计模式
设计模式学习(二十四):Spring 中使用到的设计模式 作者:Grey 原文地址: 博客园:设计模式学习(二十四):Spring 中使用到的设计模式 CSDN:设计模式学习(二十四):Spring ...
- (C/C++学习笔记) 二十四. 知识补充
二十四. 知识补充 ● 子类调用父类构造函数 ※ 为什么子类要调用父类的构造函数? 因为子类继承父类,会继承到父类中的数据,所以子类在进行对象初始化时,先调用父类的构造函数,这就是子类的实例化过程. ...
- javaweb学习总结(二十二)——基于Servlet+JSP+JavaBean开发模式的用户登录注册
一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...
- javaweb学习总结二十二(servlet开发中常见的问题汇总)
一:web应用的映射问题 通常我们从别人那里拷贝来的代码,自己会修改应用的名称,但是web映射的访问路径并没有修改,还是原来的映射. 解决方法: 工程右键--properties--myeclipse ...
- javaweb学习总结(二十五)——jsp简单标签开发(一)
一.简单标签(SimpleTag) 由于传统标签使用三个标签接口来完成不同的功能,显得过于繁琐,不利于标签技术的推广, SUN公司为降低标签技术的学习难度,在JSP 2.0中定义了一个更为简单.便于编 ...
随机推荐
- SSH下载的方法2
------------------------------下作下载方法二---------------------------------------------------String msg=n ...
- [LeetCode] Consecutive Numbers 连续的数字 --数据库知识(mysql)
1. 题目名称 Consecutive Numbers 2 .题目地址 https://leetcode.com/problems/consecutive-numbers/ 3. 题目内容 写一个 ...
- 在CentOS 5.8上搭建PPTP VPN服务
在天朝上网,vpn已经是必备之物了,我也记录一下搭建vpn服务的方法. 1. 确认内核是否支持MPPE模块MPPE用来支持Microsoft Point to Point Encryption, 包括 ...
- Unable to generate a temporary class (result=1)解决方法
Unable to generate a temporary class (result=1).error CS2001: Source file 'C:\WINDOWS\TEMP\ug5v9uxt. ...
- Error opening trace file: No such file or directory (2)
想看sharepreference保存的键值对的数据,用到单元测,运行函数总是报这种错,且看不到file explorer-->data>对应工程包的xml文件:
- 使用XCopy发布网页
链接:https://documentation.devexpress.com/#eXpressAppFramework/CustomDocument113245 In this lesson, yo ...
- stl map高效遍历删除的方法 [转]
for(:iter!=mapStudent.end():) { if((iter->second)>=aa) { //满足删除条件,删除当前结点,并指 ...
- INNO&&DELPHI
好久不弄delphi了,再次见到inno,居然不知所措~ 让人亲切的 var,又见到了.而如今,到处可见. 整目录复制 Flags: igNoreversion recursesubdirs crea ...
- 守护进程和inetd超级服务器
守护进程: 1 系统启动时,由系统初始化脚本启动.一般在/etc目录下,或者以/etc/rc开头的目录 2 许多网络服务器由inetd超级服务器启动 3 cron守护进程按规则定期执行一些程序 4 用 ...
- EasyMock使用手记
from:http://www.blogjava.net/supercrsky/articles/162766.html Mock 对象能够模拟领域对象的部分行为,并且能够检验运行结果是否和预期的一致 ...