Servlet
一、什么是Servlet?
servlet 是运行在 Web 服务器中的小型 Java 程序(即:服务器端的小应用程序)。servlet 通常通过 HTTP(超文本传输协议)接收和响应来自 Web 客户端的请求。
二、执行过程:
三、Servlet的生命周期:
Servlet是一个供其他Java程序(Servlet引擎)调用的Java类,它不能独立运行,它的运行完全由Servlet引擎来控制和调度。
针对客户端的多次Servlet请求,通常情况下,服务器只会创建一个Servlet实例对象,也就是说Servlet实例对象一旦创建,它就会驻留在内存中,为后续的其它请求服务,直至web容器退出,servlet实例对象才会销毁。
在Servlet的整个生命周期内,Servlet的init方法只被调用一次。而对一个Servlet的每次访问请求都导致Servlet引擎调用一次servlet的service方法。对于每次访问请求,Servlet引擎都会创建一个新的HttpServletRequest请求对象和一个新的HttpServletResponse响应对象,然后将这两个对象作为参数传递给它调用的Servlet的service()方法,service方法再根据请求方式分别调用doXXX方法。
四:ServletConfig的使用
作用1:可以获取servlet配置信息:
方式1:
private ServletConfig config;
public void init(ServletConfig config) throws ServletExcepiton {
this.ocnfig = config;
}
pubilc void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String value = config.getInitParameter("encoding");//encoding是配置文件中的param-name名
System.out.println(value);
方式2:
//通过使用继承父类的方法得到ServletConfig对象
String value = this.getServletConfig().getInitParameter("encoding");
System.out.println(value);
方式3:
String value = this.getInitParameter("encoding");
System.out.println(value);
作用2:可以获得ServletContext对象
五:ServletContext(重要)
ServletContext: 代表的是整个应用。一个应用只有一个ServletContext对象。单实例。
作用:
域对象:在一定范围内(当前应用),使多个Servlet共享数据
常用方法:
void setAttribute(String name,object value);//向ServletContext对象的map中添加数据
Object getAttribute(String name);//从ServletContext对象的map中取数据
void rmoveAttribute(String name);//根据name去移除数据
获取全局配置信息:
修改web.xml文件:
//配置当前应用的全局信息
<context-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</contexet-param>
//String getInitParameter(String name) //根据配置文件中的key,得到value
String encoding = sc.getInitParameter("***")//***是某个全局的param-name名
System.out.println(encoding);
获取资源路径:
String getRealPath(String path); //根据资源名称得到资源的绝对路径
可以得到当前应用任何位置的任何资源
//得到c.properties
private void test3() throws FileNotFoundException, IOException {
ServletContext sc = this.getServletContext();
String path = sc.getRealPath("/WEB-INF/classes/com/feng/Servlet/c.properties");
Properties prop = new Properties();
prop.load(new FileInputStream(path));
System.out.println(prop.getProperty("key"));
}
//得到b.properties
private void test2() throws FileNotFoundException, IOException {
ServletContext sc = this.getServletContext();
String path = sc.getRealPath("/WEB-INF/classes/b.properties");
Properties prop = new Properties();
prop.load(new FileInputStream(path));
System.out.println(prop.getProperty("key"));
}
//得到a.properties
private void test1() throws IOException {
ServletContext sc = this.getServletContext();
String path = sc.getRealPath("/WEB-INF/a.properties");//要以/开头,/代表的是当前应用
Properties prop = new Properties();
prop.load(new FileInputStream(path));
System.out.println(prop.getProperty("key"));
}
实现Servlet的转发
ServletContext sc = this.getServletContext();
RequesetDispatcher rd = sc.getRequestDispatcher("/ServletDemo2");//跳转到ServletDemo2
rd.forward(request, response);//将请求信息向下传递