Servlet开发

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();
    }
}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容