servlet.md
Servlet开发
- Servlet 是sun公司提供的一门用于开发动态web资源的技术
- 如何开发一个web动态资源?
1.编写一个Java类,实现servlet接口
2.把开发好的Java类部署到web服务器只能怪 - public abstract interface Servlet
Defines methods that all servlets must implement.
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
The servlet is constructed, then initialized with the init method.
Any calls from clients to the service method are handled.
The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.
Servlet在web应用中的位置
Servlet的调用过程
Servlet接口实现类
- 默认实现类:GenericServlet,HttpServlet
- HttpServlet指的是能够处理HTTP请求的servlet,在原有的Servlet上添加了一些与HTTP协议处理方法,比Servlet更强大
- HttpServlet在实现Servlet接口的时候,覆写了
service
方法,该方法会自动判断用户的请求 方式,如为GET请求的时候,就会调用HttpServlet的doGet方法,如为Post请求,则调用doPost方法,通常在使用的时候直接覆写doGet或者doPost方法即可 - HttpServlet API文档
java.lang.Object
java.lang.Object
|
+--javax.servlet.GenericServlet
|
+--javax.servlet.http.HttpServlet
Provides an anstract class to subclassed to create an HTTP servlet suitable for a Web site.A succlass of HTTPServlet must override at least one method,ususally one of these:
- doGet,if the servlet support HTTP GET requests
- doPost,for HTTP POST requests
- There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).
Servlet的一些细节问题
- 由于客户端是通过URL地址访问web服务器资源的,所以Servlet程序要想被外界访问,必须把servlet程序映射到一个URL地址上,通常在web.xml文件中使用<servlet>元素和<servlet-mapping>元素.
- 在3.0以后可以直接在开头直接
@WebServlet(name = "ServletResponseDemo",urlPatterns = {"/ServletResponseDemo"})
方式映射,具体请查看3.0特性 - 同一个Servlet可以被映射到多个URL上,即多个<servlet-mapping>元素的<servlet-name>子元素设置
- Servlet映射的URL中也可以使用通配符,<font color='red'>两种固定的格式.扩展名(.do),另一种是/以/*结尾(/action),映射关系中,以/开头的优先级高</font>.
Servlet的生命周期(life-cycle)
- 在Servlet的整个生命周期内,通常情况是,服务器只会创建一个Servlet实例对象,也就是说Servlet实例对象一旦被创建就会驻留内存中,为后续的其他请求服务,直至服务器关闭或者web应用退出才会销毁(destory method)
- 在Servlet的整个生命周期内,Servlet的init方法只调用一次.而对一个Servlet的每次访问请求都导致Servlet引擎调用一个servlet的service方法,<font color='green'>对于每次访问,Servlet引擎都会创建一个新的HttpServletRequest请求和一个新的HttpServletResponse相应对象,</font>然后将这两个对象作为参数传递给它调用的Servlet的service()方法,service方法再根据请求方式分别调用doXXX方法.
- <load-on-startup>元素,那么WEB应用程序在启动时,就会装载并创建Servlet的实例对象、以及调用Servlet实例对象的init()方法.例如:web应用程序以启动,框架也随之启动
ServletConfig对象
(public abstract interface ServletConfig
A servlet configuration object used by a servlet container used to pass information to a servlet during initialization.)
- 在Servlet的配置文件中,可以使用<init-param>标签为servlet配置一些初始化参数
- 当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并且调用servlet的init方法时,将servletconfig对象传递给servlet,通过ServletConfig对象就可以得到当前的初始化信息
<font color='blue'>ServletConfig作用</font>
1.获得字符集编码
2.获得数据库链接信息
3.获得配置文件
Method | Method |
---|---|
String | getInitParameter(java.lang.String name) |
Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. | |
Enumeration | getinitParameterNames |
servlaetcontext | getServletContext |
String | getServletName |
Method Summary
Method | Method |
---|---|
String | getInitParameter(java.lang.String name) |
Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. | |
Enumeration | getinitParameterNames |
servlaetcontext | getServletContext |
String | getServletName |
获取初始化参数
@WebServlet(name = "ServletConfigDemo2",urlPatterns = {"/ServletConfigDemo2"},
initParams = {@WebInitParam(name = "name",value = "xiaozi"),
@WebInitParam(name = "name1",value = "zhangsan")})
public class ServletConfigDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
ServletConfig config = this.getServletConfig();
//初始化
String value = config.getInitParameter("name");
response.getOutputStream().write(value.getBytes());
}
}
获取所有的初始化参数
package ConfigEx;
import javax.servlet.*;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
/**
* Created by tg
*/
@WebServlet(name = "ServletConfig2",urlPatterns={"/ServletConfig2"},
initParams = {@WebInitParam(name = "name",value="xiaolizi"),
@WebInitParam(name = "name1",value = "zhangsan")})
public class ServletConfig2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
javax.servlet.ServletConfig config = this.getServletConfig();
//获取所有的初始化参数
Enumeration enumeration = config.getInitParameterNames();
//
while (enumeration.hasMoreElements()){
String name = (String) enumeration.nextElement();
String value = config.getInitParameter(name);
response.getOutputStream().write((name+" = "+value+"<br/>").getBytes());
}
}
}
ServletContext
*Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
- web容器启动时,它会为每个webi应用程序都创建一个对象的ServletContext对象,代表当前web应用
- The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.(ServletConfig对象中维护了ServletContext对象的引用,在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象)
- 由于一个web应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯
#######ServletContext的应用
- 多个Servlet通过ServletContext对象实现数据共享
- 获取web应用的初始化参数
- 实现Servlet的转发
- 利用ServletContext对象读取资源文件
1.得到文件路径
2.读取资源文件的三种方式
3.properties文件(属性文件) - 缓存Servlet的输出
在servlet中设置合理的缓存时间,以避免浏览器频繁向服务器发送请求,提升服务器的性能
数据共享
实现Demo1和Demo2数据共享
package ConfigEx.ServletContext;
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;
import java.io.IOException;
/**
-
Created by tg
-
数据共享
*/
@WebServlet(name = "ServletContextDemo1",urlPatterns = {"/ServletContextDemo1"})
public class ServletContextDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "abc"; ServletContext context = this.getServletConfig().getServletContext(); // Binds an object to a given attribute name in this servlet context. context.setAttribute("data",data);
}
}
package ConfigEx.ServletContext;
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;
import java.io.IOException;
/**
-
Created by tg
*/
@WebServlet(name = "ServletContextDemo2",urlPatterns = {"/ServletContextDemo2"})
public class ServletContextDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext(); //Returns the servlet container attribute with the given name, or null if there is no attribute by that name. String data= (String) context.getAttribute("data"); System.out.println(data);
}
}
#####获取整个站点的初始化参数
package ConfigEx.ServletContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
-
Created by tg
*/
@WebServlet(name = "ServletContextDemo3",urlPatterns = {"/ServletContextDemo3"},
initParams = {@WebInitParam(name = "url",value="xiaolizi")
})
public class ServletContextDemo3 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); System.out.println(url); response.getOutputStream().write(url.getBytes());
}
}
######对应用进行转发
package cn.tg.ServletContext;
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;
import java.io.IOException;
import java.io.OutputStream;
/**
- Created by tg
- 对应用进行转发,用ServletContext进行转发mvc
- 注意:
1.跳转之前的任何写入都无效,跳转之后的也无效
2.转发之前response不能提交,否则转发的时候服务器会抛异常
*/
@WebServlet(name = "ServletContextDemo4",urlPatterns = {"/ServletContextDemo4"})
public class ServletContextDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* 将数据进行转发,servlet不适合输出,可以转发给jsp,此段代码并不会执行
String data = "aaabbbcccdd";
response.getOutputStream().write(data.getBytes());
OutputStream out = response.getOutputStream();
out.write("111".getBytes());
out.close();*/
//拿到ServletContext
ServletContext context = this.getServletContext();
//获取转发对象
RequestDispatcher rd = context.getRequestDispatcher("/ServletContextDemo5");
rd.forward(request,response);//4,5共享同一个request,response.
}
}
package cn.tg.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;
import java.io.IOException;
/**
-
Created by tg
*/
@WebServlet(name = "ServletContextDemo5",urlPatterns = {"/ServletContextDemo5"})
public class ServletContextDemo5 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "abcdefghijklmn"; response.setDateHeader("expires",System.currentTimeMillis()+24*3600*1000); //回送给浏览器 response.getOutputStream().write(data.getBytes());
}
}
#####读取资源
<font color="red">类装载器读取文件
与读取大文件</font>
package cn.tg.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;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
- Created by tg
- 类装载器读取资源文件
*/
@WebServlet(name = "ServletContextDemo7",urlPatterns = {"/ServletContextDemo7"})
public class ServletContextDemo7 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
test2();
}
private void test1() throws IOException {
//获取到装载当前类的类装载器
ClassLoader loader = ServletContextDemo7.class.getClassLoader();
InputStream in = loader.getResourceAsStream("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");
System.out.println(username);
}
//类路径下面包下面的资源文件
private void test2() throws IOException{
//获取到装载当前类的类装载器
InputStream loader = ServletContextDemo7.class.getClassLoader()
.getResourceAsStream("/db.properties");
System.out.println(loader);
}
//通过类装载器读取资源文件的注意事项:不适合大文件的读取
private void test3(){
}
//如何读取大文件?******只能用ServletContext
private void test4() throws IOException {
//得到文件地址
String path = this.getServletContext().getRealPath("");
String filename = path.substring(path.lastIndexOf("\\")+1);
InputStream in = this.getServletContext().getResourceAsStream("");
//定义缓冲
byte []buffer = new byte[1024];
int len = 0;
FileOutputStream out = new FileOutputStream("e://"+filename);
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
out.close();
in.close();
}
}
}
网友评论