zoukankan      html  css  js  c++  java
  • 关于Servlet的总结

    HTTP的请求协议的全部信息被自动封装到javax.servlet.http.HttpServletRequest对象中。
          在HttpServletRequest接口类型中有一个方法叫做:String getMethod();可以获取请求方式。
          public interface javax.servlet.http.HttpServletRequest extends ServletRequest{
          }

    前端页面提交的【post】数据以[key-value]的Map方式封装在HttpServletRequest的对象中,可以使用HttpServletRequest

    中的方法取出。request对象的生命周期比较短暂【Seesion、Application等域属性相比】

    一次请求创建一个请求对象,一个servlet对象,一个servletConfig对象。

    public abstract class HttpServlet extends GenericServlet   implements java.io.Serializable {

    }

    public abstract class GenericServlet implements Servlet, ServletConfig, java.io.Serializable {

    }

    public interface Servlet {

    }

    public interface ServletConfig {

    }

    public interface HttpServletRequest extends ServletRequest {

    }

    public interface ServletRequest {

    }

    抽象类HttpServlet类型是继承GenericServlet抽象类,GenericServlet实现了接口Servelt和ServletConfig接口。

    GenericServlet提供一个适配器功能,将不经常使用的Servlet方法抽出,方面编程。

    HttpServlet提供一个模版设计模式,在前端页面提交【GET、POST】都可以获得相应的提示。

    public class HttpServlet extends GenericServlet {
    
        @Override
        public void service(ServletRequest req, ServletResponse res)
                throws ServletException, IOException {
    //由于Tomcat服务会实现HttpServletRequest接口,并将请求提交的数据都封装到HttpServeltRequest对象中,
    //所以在HttpServelt的Service方法里
    先把参数强转为HttpServletRequest类型,
    //再提供一个参数为HttpServletRequest的service方法。在这个service方法中做出提交方式的判断,和响应。
    HttpServletRequest request
    = (HttpServletRequest)req; HttpServletResponse response=(HttpServletResponse)res; service(request,response); } public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { String method = request.getMethod(); if("GET".equals(method)){ doGet(request,response); }else{ doPost(request,response); } } private void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("错误!GET"); throw new RuntimeException(""); } private void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("错误!POST"); throw new RuntimeException(""); } }

    在实现HttpServlet时根据提交数据的内容,重写doGet或doPost方法,根据Java的多态属性,重写后会执行重写后的doGet或doPost的方法。

  • 相关阅读:
    如何讓你的程序在退出的時候執行一段代碼?
    05_Python爬蟲入門遇到的坑__總結
    04_Python爬蟲入門遇到的坑__向搜索引擎提交關鍵字02
    03_Python爬蟲入門遇到的坑__向搜索引擎提交關鍵字01
    02_Python爬蟲入門遇到的坑__反爬蟲策略02
    01_Python爬蟲入門遇到的坑__反爬蟲策略01
    Python爬蟲--rrequests庫的基本使用方法
    C#筆記00--最基礎的知識
    為元組中的每一個元素命名
    Filter函數
  • 原文地址:https://www.cnblogs.com/flytogalaxy/p/7908770.html
Copyright © 2011-2022 走看看