ServletConfig与ServletContext对象(接口)
ServletConfig:封装servlet的配置信息。
在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数。
<servlet>
<servlet-name>ServletDemo4</servlet-name>
<servlet-class>cn.itcast.web.servlet.ServletDemo4</servlet-class>
<init-param> <!-- servletConfig -->
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param> <!-- servletConfig -->
<param-name>xxx</param-name>
<param-value>yyy</param-value>
</init-param>
</servlet>
当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以得到当前servlet的初始化参数信息。
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//通过servletCOnfig获取servlet配置的初始化参数
public class ServletDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletConfig config = this.getServletConfig();
//获取配置的初始化参数的方式1
//String value = config.getInitParameter("charset");
Enumeration e = config.getInitParameterNames();
while(e.hasMoreElements()){
String name = (String) e.nextElement();
String value = config.getInitParameter(name);
System.out.println(name + "=" + value);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
应用场景:
获得字符集编码(编码是配置的,最好不要写死)
获得数据库连接信息
获得配置文件,查看struts案例的web.xml文件
ServletContext:代表当前web应用。即每个web应用都对应一个ServletContext
WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得代表当前web应用的 ServletContext对象。
由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。
ServletContext对象通常也被称之为context域对象。(即该对象作用范围为:整个web应用生命周期内)
获取代表当前web应用的ServletContext对象的方式:
1.ServletContext context=this.getServletConfig().getServletContext();
2.从父类继承而来
ServletContext context= this.getServletContext();
类似ServletConfig的获取方式
ServletConfig config = this.getServletConfig();
ServletContext应用:
1. 多个Servlet通过ServletContext对象实现数据共享。
ServletContext context= this.getServletContext();
context.setAttribute("data","aa");//在一个servlet中设置值
context.getAttribute("data");//在另一个servlet中可以获取该值。
2. 通过ServletContext获取WEB应用的初始化参数。
<!-- 为web应用设置初始化参数,这些设置的初始化参数可以通过servletContext对象的getInitParameter()方法获取 -->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>root</param-value>
</context-param>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//通过servletContext,获取为web应用配置的初始化参数
public class ServletDemo7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//String value = this.getServletContext().getInitParameter("xxx");
String url = this.getServletContext().getInitParameter("url");
String username = this.getServletContext().getInitParameter("username");
String password = this.getServletContext().getInitParameter("password");
System.out.println(url);
System.out.println(username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
3.获取文件的mime类型
//通过servletContext获取文件的mime类型
public class ServletDemo8 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filename = "1.jpg";
ServletContext context = this.getServletContext();
System.out.println(context.getMimeType(filename));//获取指定文件的mime类型
response.setHeader("content-type", "image/jpeg");//如果已经知道输出的文件的mime类型,可以这么写
response.setHeader("content-type",context.getMimeType(filename));//如果不知道文件类型,可以先通过ServletContext获取
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
4. 通过servletContext 实现请求转发 。(MVC设计模式)
//servlet收到请求产生数据,然后转交给jsp显示
String data = "aaaaaa"; this.getServletContext().setAttribute("data", data); RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/view.jsp");//得到转发请求对象 rd.forward(request, response);
5. 利用ServletContext对象读取资源文件。
得到文件路径
读取资源文件的三种方式
.properties文件(属性文件)
getRealPath(string path)---根据web应用中的相对路径得到在硬盘的物理路径(绝对路径)。用来在web工程中读取文件。
getResource(string path)--根据路径获取url
getResourceAsStream(path)
getResourcePaths(path)
读取资源文件的三种方式: 资源文件在Eclipse web工程的WebRoot根目录下。
//读取配置文件的第一种方式,相对路径
private void test1() throws IOException {
ServletContext context = this.getServletContext();
InputStream in = context.getResourceAsStream("/db.properties");//db.properties在WebRoot根目录下。/ 代表web应用根目录
Properties prop = new Properties(); //map
prop.load(in);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
//读取配置文件的第二种方式,得到物理路径
private void test2() throws IOException {
ServletContext context = this.getServletContext();
String realpath = context.getRealPath("/db.properties"); //c:\\sdsfd\sdf\db.properties
//获取到操作文件名 realpath=abc.properties
String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
System.out.println("当前读到的文件是:" + filename);
FileInputStream in = new FileInputStream(realpath);
Properties prop = new Properties();
prop.load(in);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println("文件中有如下数据:");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
//读取配置文件的第三种方式
private void test3() throws IOException {
ServletContext context = this.getServletContext();
URL url = context.getResource("/db.properties");
InputStream in = url.openStream();
....
//下面代码用方式一,二的模板代码
}
读取的资源文件在eclipse web工程中src文件夹里。该如何读???
//读取src下面的配置文件(传统方式FileInputStream不可取)
private void test4() throws IOException {
FileInputStream in = new FileInputStream("src/db.properties");//src目录里的文件发布时,会部署到WebRoot根目录里的WEB-INF里的classes文件夹下。
System.out.println(in);
}
上面即使改为: FileInputStream in = new FileInputStream("/WEB-INF/classes/db.properties");也不行,因为这里的相对路径,是指相对JVM的启动路径。
即tomcat的bin目录。startup.bat所在的目录。
正确的方式为:
//读取src下面的配置文件
private void test5() throws IOException {
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties(); //map
prop.load(in);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
下面是超级重要的东西:
在web工程的普通java程序中如何读取资源文件
如数据库访问层的包中放置了数据库的配置文件db.properties,由于该包中的文件是普通的java程序,不是上面所说的servlet,
那么在开发中该如何读取呢???
用类装载器去读,类装载器只能装载类目录下的文件,即db.properties只能在src目录下,不能放在WebRoot根目录下。
package cn.itcast.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
//在web工程的普通java程序中如何读取资源文件
public class StudentDao { //不是servlet
public String get() throws IOException { //类装载器读
test1();
test2();
return null;
}
//以下代码在读文件时,可以读到更新后的文件,用类装载器去读取文件位置,数据依然用传统方式去读。
public void test2() throws IOException{
ClassLoader loader = StudentDao.class.getClassLoader();//得到该类的类装载器
URL url = loader.getResource("cn/itcast/dao/db.properties");//用类装载器的方法区装载
String filepath = url.getPath();//得到文件在硬盘的绝对路径,之后可以用传统方式去读
FileInputStream in = new FileInputStream(filepath);
Properties prop = new Properties(); //map
prop.load(in);
String dburl = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(dburl);
System.out.println(username);
System.out.println(password);
}
//以下代码在读文件时,读到不到更新后的文件
public void test1() throws IOException{
ClassLoader loader = StudentDao.class.getClassLoader();
InputStream in = loader.getResourceAsStream("cn/itcast/dao/db.properties");
Properties prop = new Properties(); //map
prop.load(in);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
}
注意:
如果db.properties在src的根目录,路径写法:
loader.getResourceAsStream("db.properties");
如果db.properties在package cn.itcast.dao里,路径写法:
loader.getResourceAsStream("cn/itcast/dao/db.properties");
通过类装载器读文件时,需要注意的问题:不能装载大文件,否则会内存溢出。
如果文件很大,可以使用类装载器获得路径,然后用传统io方式去读。
getServletContextName()方法:获取web.xml配置文件中配置的web应用的名称
<display-name>sina</display-name>
应用场景:
//获取web.xml文件中配置的web应用的显示名称
public class ServletDemo13 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = this.getServletContext().getServletContextName();
response.getWriter().write("<a href='/"+name+"/1.html'>点点</a>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
对于不经常变化的数据,在servlet中可以为其设置合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能。
//设置浏览器的缓存
public class ServletDemo14 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long expriestime = System.currentTimeMillis() + 1*24*60*60*1000;
response.setDateHeader("expires", expriestime);
String data = "adsdfsdfsdfsdfdsf";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletConfig与ServletContext对象(接口)的更多相关文章
- day05 Servlet 开发和 ServletConfig 与 ServletContext 对象
day05 Servlet 开发和 ServletConfig 与 ServletContext 对象 1. Servlet 开发入门 - hello world 2. Servlet 的调用过程和生 ...
- ServletConfig与ServletContext对象详解
一.ServletConfig对象 在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数.(配置在某个servlet标签或者整个w ...
- javaWEB总结(4):ServletContext对象方法
前言:之前每次学到ServletContext对象都会抗拒,跳着学,后面才发现有很多不懂的原理都在这个对象里面,后悔莫及,所以今天特地把他单放在一篇文章里,算是对他的忏悔. 1.什么是ServletC ...
- ServletConfig与ServletContext
ServletConfig与ServletContext对象详解 一.ServletConfig对象 在Servlet的配置文件中,可以使用一个或多个<init-param>标签为s ...
- mvc-servlet---ServletConfig与ServletContext对象详解(转载)
ServletConfig与ServletContext对象详解 一.ServletConfig对象 在Servlet的配置文件中,可以使用一个或多个<init-param>标签为s ...
- 一、HttpServletRequest接口 二、HttpServletReponse接口 三、POST和GET请求方式及其乱码处理 四、ServletContext对象和ServletConfig对象
一.HttpServletRequest接口 内部封装了客户端请求的数据信息 接收客户端的请求参数.HTTP请求数据包中配置参数 ###<1>常用方法 getContextPath()重要 ...
- Servlet接口的实现类,路径配置映射,ServletConfig对象,ServletContext对象及web工程中文件的读取
一,Servlet接口实现类:sun公司为Servlet接口定义了两个默认的实现类,分别为:GenericServlet和HttpServlet. HttpServlet:指能够处理HTTP请求的se ...
- Java Servlet(三):Servlet中ServletConfig对象和ServletContext对象
本文将记录ServletConfig/ServletContext中提供了哪些方法,及方法的用法. ServletConfig是一个抽象接口,它是由Servlet容器使用,在一个servlet对象初始 ...
- 小谈-—ServletConfig对象和servletContext对象
一.servletContext概述 servletContext对象是Servlet三大域对象之一,每个Web应用程序都拥有一个ServletContext对象,该对象是Web应用程序的全局对象或者 ...
随机推荐
- 高精度之+×÷
以下是三种高精度算术的模版: 高精度加法: ",s1,s2; ],ss2[],len; void dashu(string s1,int ss1[]) { ;i>=;i--) { ;j ...
- web.py 学习(二)Worker
Rocket Server 启动一个线程监听客户端的连接,收到连接将连接放置到队列中.线程池中的Worker会以这个连接进行初始化.Rocket中Worker的基类是: class Worker(Th ...
- ESFramework ——可堪重任的网络通信框架
ESFramework是一套性能卓越.稳定可靠.强大易用的跨平台通信框架,支持应用服务器集群.其内置了消息的收发与自定义处理(支持同步/异步模型).消息广播.P2P通道.文件传送(支持断点续传).心跳 ...
- JQuery 阻止事件冒泡
JQuery 提供了两种方式来阻止事件冒泡. 方式一:event.stopPropagation(); $("#div1").mousedown(function(event){ ...
- 【python问题系列--2】脚本运行出现语法错误:IndentationError: unindent does not match any outer indentation level
缩进错误,此错误,最常见的原因是行之间没有对齐. 参考:http://www.crifan.com/python_syntax_error_indentationerror/comment-page- ...
- ***1133. Fibonacci Sequence(斐波那契数列,二分,数论)
1133. Fibonacci Sequence Time limit: 1.0 secondMemory limit: 64 MB is an infinite sequence of intege ...
- 3. 编写Java应用程序,定义Animal类,此类中有动物的属性:名称 name,腿的数量legs,统计动物的数量 count;方法:设置动物腿数量的方法 void setLegs(),获得腿数量的方法 getLegs(),设置动物名称的方法 setKind(),获得动物名称的方法 getKind(),获得动物数量的方法 getCount()。定义Fish类,是Animal类的子类,统计鱼的数量
//Animal 类 package d922B; public class Animal { private String kind; private int legs,count; public ...
- Sql sever 常用语句(续)
distintct: 查询结果排除了重复项(合并算一项)--如查姓名 select distinct ReaName from UserInfo 分页语句:(查询区间时候应该查询出行号,作为分页的 ...
- hdu_1728_逃离迷宫(bfs)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1728 题意:走迷宫,找最小的拐角 题解:对BFS有了新的理解,DFS+剪枝应该也能过,用BFS就要以拐 ...
- cmstop传递什么控制器和方法---就实例化该控制器
object顶级类class object 第一级抽象类controllerabstract class controller extends object 第二级抽象类controller_abst ...