一、ServletConfig对象
1.1获取一个servletConfig对象
1)通过初始化方法获得一个servletconfig
2)通过继承父类(GenericServlet.)得到一个servletconfig对象
1.2servletConfig对象的作用
1)getServletName():返回servlet实例的名称
2)getServletContext():获取一个servletContext对象
3)getInitParameter(String):获取servlet中初始化参数的值。
1.3config使用
在servlet的web.xml配置文件中,可以在配置文件中生成一个<init-param>标签为servlet设置一些初始化参数,这里需要写上映射路径,不然资源显示不可用。
<servlet>
<servlet-name>test4</servlet-name>
<servlet-class>Config.ServletConfigDemo1</servlet-class>
<init-param>
<param-name>name1</param-name>
<param-value>gucci</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123</param-value>
</init-param>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>test4</servlet-name>
<url-pattern>/ConfigDemo</url-pattern>
</servlet-mapping>
当我们在servlet的配置文件设置了之后,web容器在创建servlet实例对象后,会自动将这些初始化参数封装到servletconfig对象中,并调用servlet中的
init方法,将servletconfig对象传给servlet。然后我们通过servletconfig对象就可以获得这些初始化参数。
package Config; 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; public class ServletConfigDemo1 extends HttpServlet { /**
* 定义ServletConfig对象来接收配置的初始化参数
*/
private ServletConfig config; /**
* 当servlet配置了初始化参数后,web容器在创建servlet实例对象时,
* 会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,
* 将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以
* 得到当前servlet的初始化参数信息。
*/
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取在web.xml中配置的初始化参数
String paramVal = this.config.getInitParameter("name1");//获取指定的初始化参数
response.getWriter().print(paramVal); response.getWriter().print("<hr/>");
//获取所有的初始化参数
Enumeration<String> e = config.getInitParameterNames();
while(e.hasMoreElements()){
String name = e.nextElement();
String value = config.getInitParameter(name);
response.getWriter().print(name + "=" + value + "<br/>");
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
} }
运行结果如图:
二、servletconfig对象
WEB容器在启动时,它会为,每个web应用程序都创建一个servletconfig对象,它代表当前web应用。
servletconfig对象中维护了servletcontext对象的引用。在编写servlet时,可以通过servletconfig.getservletcontext方法获得servletcontext对象。
由于一个web应用中所有的servlet共用一个servletcontext对象,因此servlet对象之间可以通过servletcontext对象来实现通讯,servletcontext对象也通常
被称为域对象。
三、servletcontext的应用
3.1多个servlet通过servletcontext对象实现数据共享
package Test1; import java.io.IOException; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ServletContextDemo1")
public class ServletContextDemo1 extends HttpServlet{ private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.setAttribute("name", "duck");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package Test1; import java.io.IOException; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ServletContextDemo2")
public class ServletContextDemo2 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletConfig().getServletContext();
// 获取设置在servletcontext中保存好的参数
String name = (String)context.getAttribute("name");
resp.getWriter().print(name);
System.out.println(name); }
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
removeAttribute(String name):也可以通过名称来移除内容
3.2获取全局配置信息和获取web项目资源
package Test1; import java.io.IOException; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ServletContextDemo3
*/
@WebServlet("/ServletContextDemo3")
public class ServletContextDemo3 extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
// 利用servletcontext获取web.xml文件中设置的初始化参数
String str = context.getInitParameter("encoding");
response.getWriter().print(str);
response.getWriter().print("<br/>");
// 根据资源名得到资源的决定路径
String path = context.getRealPath("/WEB-INF/web.xml");
response.getWriter().print(path);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }
3.3用servletcontext实现请求转发
package Test1; import java.io.IOException; import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ServletContextDemo6
*/
@WebServlet("/ServletContextDemo6")
public class ServletContextDemo6 extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public ServletContextDemo6() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = this.getServletContext();
RequestDispatcher rs = sc.getRequestDispatcher("/ServletContextDemo2");
// 将请求信息向下传递
rs.forward(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
3.4利用servletcontext读取资源文件
package Test1; import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ServletContextDemo4
*/
@WebServlet("/ServletContextDemo4")
public class ServletContextDemo4 extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* response.setContentType("text/html;charset=UTF-8");
* 目的是控制浏览器用utf-8进行解码,这样就不会出现中文乱码了
*/
response.setHeader("content-type", "text/html;charaset=UTF-8");
read(response);
}
public void read(HttpServletResponse response) throws IOException {
// 获取在src下面的文件
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/Test1/db.properties");
// 创建一个properties
Properties prop = new Properties();
// 加载字节流
prop.load(in);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
// 设置好输出格式
response.getWriter().print(
MessageFormat.format("driver={0},url={1},username={2},password={3}",
driver,url,username,password)
);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
driver=com.mysql.jdbc.Driver
url=jdbc:mysql//localhost3306//test
username=root
password=root
3.5使用servletcontext读取指定路径下的所有内容
package Test1; import java.io.IOException;
import java.util.Iterator;
import java.util.Set; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ServletContextDemo5
*/
@WebServlet("/ServletContextDemo5")
public class ServletContextDemo5 extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public ServletContextDemo5() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取指定路径下的所有内容
Set set = this.getServletContext().getResourcePaths("/WEB-INF");
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }