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的方法。

  • 相关阅读:
    virtual
    微软MBS intern笔试
    Ubuntu Linux Green hand
    Coding style
    abstract
    Jquery Ajax请求标准格式
    Hashtable的简单实用
    C#中GET和POST的简单区别
    WIN7 64位机与32位机有什么区别
    一个加密解密类
  • 原文地址:https://www.cnblogs.com/flytogalaxy/p/7908770.html
Copyright © 2011-2022 走看看