Servlet相关常用类

包括:

一.Servlet体系

二.ServletContext接口和ServletConfig接口

一.Servlet体系
    如下图所示:

    总共3个类:Servlet接口,GenericServlet抽象类,HttpServlet抽象类。

1.1 Servlet 接口
    对于Servlet接口,有5个方法,如下:
public interface Servlet {
    public void init(ServletConfig config) throws ServletException;
    public ServletConfig getServletConfig();
 
    public void service(ServletRequest req, ServletResponse res)
      throws ServletException, IOException;
 
    public String getServletInfo();
    public void destroy();
}

    解释:
  • init():初始化方法
  • getServletConfig():可以得到一个ServletConfig对象,利用这个参数可以得到初始化参数
  • service():servlet对于请求的一个响应
  • getServletInfo():返回servlet的相关信息
  • destroy():销毁Servlet。

1.2 GenericServlet 抽象类
   它是一个抽象类。实现了Servlet接口方法的init()方法,但是最重要的service()方法并没有实现 。如下代码:
public void init(ServletConfig config) throws ServletException {
    this.config = config;
    this.init();
}
public void init() throws ServletException {
}


1.3 HttpServlet 抽象类
    它是一个抽象类。实现了Servlet接口的service()方法。在service()方法中,根据一定的条件分发到doGet()或者doPost()方法中。
主要代码如下:
    protected void service(HttpServletRequest req, HttpServletResponse resp)  
        throws ServletException, IOException {  
      
        String method = req.getMethod();  
      
        if (method.equals(METHOD_GET)) {  
            long lastModified = getLastModified(req);  
            if (lastModified == -1) {  
                // servlet doesn't support if-modified-since, no reason  
                // to go through further expensive logic  
                doGet(req, resp);  
            } else {  
                long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);  
                if (ifModifiedSince < (lastModified / 1000 * 1000)) {  
                    // If the servlet mod time is later, call doGet()  
                    // Round down to the nearest second for a proper compare  
                    // A ifModifiedSince of -1 will always be less  
                    maybeSetLastModified(resp, lastModified);  
                    doGet(req, resp);  
                } else {  
                    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);  
                }  
            }  
      
        } else if (method.equals(METHOD_HEAD)) {  
            long lastModified = getLastModified(req);  
            maybeSetLastModified(resp, lastModified);  
            doHead(req, resp);  
      
        } else if (method.equals(METHOD_POST)) {  
            doPost(req, resp);  
              
        } else if (method.equals(METHOD_PUT)) {  
            doPut(req, resp);          
              
        } else if (method.equals(METHOD_DELETE)) {  
            doDelete(req, resp);  
              
        } else if (method.equals(METHOD_OPTIONS)) {  
            doOptions(req,resp);  
              
        } else if (method.equals(METHOD_TRACE)) {  
            doTrace(req,resp);  
              
        } else {  
            //  
            // Note that this means NO servlet supports whatever  
            // method was requested, anywhere on this server.  
            //  
      
            String errMsg = lStrings.getString("http.method_not_implemented");  
            Object[] errArgs = new Object[1];  
            errArgs[0] = method;  
            errMsg = MessageFormat.format(errMsg, errArgs);  
              
            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);  
        }  
    }  

    一般来说,我们自定义自己的servlet就继承HttpServlet,再重写doGet(),doPost()方法即可。


二.ServletContext接口和ServletConfig接口

2.1 ServletContext接口
    WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
    ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象

ServletContext作用:
1. 用于Servlet之间通讯
    由于 一个WEB应用中的所有Servlet共享同一个ServletContext对象 ,因此 Servlet对象之间可以通过ServletContext 对象来实现通讯。如代码: context.setAttribute("name", "haha");  ~~~~~~~~~~String name = context.getAttribute("name");   

2. 用于获取WEB应用的初始化参数
    比如在web.xml中,有如下初始化:
<context-param>   

    <param-name>url</param-name>   

    <param-value>jdbc:mysql://localhost:3306/4g</param-value>   

</context-param>  
 
     即可用如下代码获得初始化参数:
String url = context.getInitParameter("url");



3.用于Servlet转发
RequestDispatcher  rd  = context.getRequestDispatcher("/index.jsp");   
rd.forward(request, response); 


Ps:转发有3种方式:
  1. forward方法:request.getRequestDispatcher("/url").forward(request, response),地址栏不会改变,同样是在服务器端完成,仅输出被转发的URL中的内
  2. sendRedirect方法:只是客户重新发起一个请求,第二个请求指向其参数url。一般称做重定向,客户端的地址栏将改变为url值,是由客户端发起的第二次请求。例如:response.sendRedirect(request.getContextPath()+"/login.html"); 
  3. iinclude方法:使原先的Servlet和转发到的Servlet都可以输出响应信息,即原先的Servlet还可以继续输出响应信息。也就是说可以保留原先的信息。

2.2 ServletConfig接口
ServletConfig 是一个接口。
    在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数。(配置在某个servlet标签或者整个web-app下)
    当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以得到当前servlet的初始化参数信息。


参考:
1.ServletConfig与ServletContext对象详解:http://blog.sina.com.cn/s/blog_696024a90100o6hq.html



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Servlet API是Java Web开发的核心,它提供了一系列的接口和来处理HTTP请求和响应。下面是Servlet API编程常用的接口: 1. Servlet接口 Servlet接口定义了一个服务方法service(),用于处理客户端的请求。开发者只需要继承该接口,实现service()方法即可编写Servlet组件。 2. HttpServletRequest接口 HttpServletRequest接口封装了HTTP请求的所有信息,包括请求头、请求参数、请求方法、请求URL等。开发者可以通过该接口提供的方法获取这些信息。 3. HttpServletResponse接口 HttpServletResponse接口封装了HTTP响应的所有信息,包括响应头、响应状态码、响应内容等。开发者可以通过该接口提供的方法设置这些信息。 4. HttpSession接口 HttpSession接口封装了一个会话的所有信息,包括会话ID、创建时间、最后访问时间等。开发者可以通过该接口提供的方法读写会话中的数据。 5. ServletConfig接口 ServletConfig接口封装了Servlet组件的配置信息,包括Servlet名称、初始化参数等。开发者可以通过该接口提供的方法获取这些信息。 6. ServletContext接口 ServletContext接口封装了整个Web应用程序的上下文信息,包括应用程序的全局参数、资源路径、Servlet组件等。开发者可以通过该接口提供的方法获取这些信息。 7. RequestDispatcher RequestDispatcher用于在Servlet组件之间进行请求转发,即将请求转发给另一个Servlet或JSP页面进行处理。 8. Cookie Cookie封装了HTTP请求和响应中的Cookie信息,开发者可以通过该提供的方法读写Cookie信息。 9. HttpServlet HttpServletServlet接口的抽象实现,开发者可以继承该编写Servlet组件。该提供了一些常用的方法,如doGet()、doPost()等,用于处理HTTP请求和响应。 以上就是Servlet API编程常用的接口和。在Java Web开发中,开发者需要熟练掌握这些接口和的使用,才能编写出高效、可靠的Web应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值