• 开发servlet三种方式


    第一种:实现Servlet接口

     

    ServletDemo类

    实现Servlet接口

    public class ServletDemo implements Servlet {
    
    //初始化该servlet()
    //只会被调用一次(当用户第一次访问该servlet时被调用)。
    @Override
    public void init(ServletConfig config) throws ServletException {
    //1.获取当前Servlet的配置信息,即web.xml中的init-param节点
    String user = arg0.getInitParameter("user");
            Enumeration<String> names = arg0.getInitParameterNames();

    //2.获取Servlet的名称,即web.xml中的servlet-name节点的值
    String servletName = arg0.getServletName();

    //3.获取ServletContext对象
            ServletContext servletContext = arg0.getServletContext();

    //3.1.获取web应用的配置信息,即web.xml中的context-param节点
    String driver = servletContext.getInitParameter("driver");
            Enumeration<String> names1 = servletContext.getInitParameterNames();

    //3.2.得到当前web应用下的某一文件在服务器上的绝对路径
            String realPath = servletContext.getRealPath("a.txt");

            //3.3.获取当前项目的名称
            String contextPath = servletContext.getContextPath();
            
            //3.4.获取当前Web应用的某一文件对应的输入流
            InputStream inputStream = servletContext.getResourceAsStream("/WEB_INF/classes/f.txt"); }
    //得到配置文件 @Override
    public ServletConfig getServletConfig() { // TODO Auto-generated method stub return null; }
    //这个函数用于处理业务逻辑
    //程序员应当把业务逻辑写在这里
    //会被调用多次,当用户每访问该servlet时,都会被调用
    //req用于获得客户端(浏览器(b/s结构))的信息,res用于向客户端(浏览器)返回信息
    @Override
    public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException {
    //RequestAPI
    // 1.根据name获取对应的请求值
            String user = request.getParameter("user");
            String pwd = request.getParameter("password");

            // 2.根据name获取多个请求值(用于CheckBox)
            String[] interestings = request.getParameterValues("interesting");

            // 3.获取全部参数名
            Enumeration<String> names = request.getParameterNames();

            // 4.获取全部参数和值(键值对形式)
            Map<String, String[]> map = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                System.out.println("**" + entry.getKey() + ":" + Arrays.asList(entry.getValue()));
            }

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            // 5.获取请求的URI
            String requstURI = httpServletRequest.getRequestURI();

            // 6.获取请求的方式(POST OR GET)
            String method = httpServletRequest.getMethod();
            
            // 7.若是GET方式,则获取请求参数字符串(问号后的)
            String queryString = httpServletRequest.getQueryString();

            // Response
            // 1.设置响应的内容类型
            response.setContentType("application/msword");

            // 2.页面上输出
            PrintWriter writer = response.getWriter();
            writer.println("helloWorld!!!"); }

    // 得到Servlet的相关信息 @Override
    public String getServletInfo() { // TODO Auto-generated method stub return null; }
    //销毁servlet实例(释放内存) @Override
    public void destroy() { // TODO Auto-generated method stub }

    //构造函数,当第一次访问服务器的时候servlet容器会创建一个servlet实例,再次访问并不会再创建,所以Servlet是单实例的
    public ServletDemo(){

    }
    }

    配置和映射Servlet

    • 两个servlet-name必须相同,名称可随意
    • servlet-class为 ServletDemo类的全类名
    • url-pattern为映射名:名称随意,"/"表示根目录
    • 配置完后可通过 localhost:8080/项目名/servletdemo 可访问
    <?xml version="1.0" encoding="UTF-8"?>
        <web-app version="2.5"
            xmlns="http://java.sun.com/xml/ns/javaee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
    <!-- 配置ServletContext -->
        <context-param>
            <param-name>driver</param-name>
            <param-value>com.mysql.jdbc.Driver</param-value>
        </context-param>
        
        <context-param>
            <param-name>jdbcUrl</param-name>
            <param-value>jdbc:mysql</param-value>
        </context-param>
    <!-- 配置和映射 Servlet --> <servlet> <servlet-name>Test</servlet-name> <servlet-class>com.zhang.ServletDemo</servlet-class>

    <!-- 配置Servlet的初始化参数,必须在load-on-startup节点之前 -->
    <init-param>
    <param-name>user</param-name>
    <param-value>root</param-value>
    </init-param>
    <init-param>
    <param-name>password</param-name>
    <param-value>123</param-value>
    </init-param>

    <!--
    指定Servlet被创建的顺序
    若为>=0,则在当前Web应用被Servlet容器加载时创建该Servlet实例(若为负数则还是在第一次访问服务器时创建)
    数值越小越早被创建
    -->
    <load-on-startup>0</load-on-startup>
    </servlet>
    <!-- 一个servlet节点可以和多个servlet-mapping节点相匹配,也就是说一个servlet可以有多个虚拟路径 -->
    <servlet-mapping> <servlet-name>Test</servlet-name> <url-pattern>/servletdemo</url-pattern> </servlet-mapping> </web-app>

    第二种:继承抽象类形式 GenericServlet

    GenericServlet类原理

    GenericServlet类实现了Servlet接口、ServletConfig接口和Serializable接口

    并在Init(ServletConfig config)方法中获得了ServletConfig对象从而实现ServletConfig接口中的getInitParameter(String name)、getServletContext()等方法

    这就意味着:

    • 继承GenericServlet类的子类只需要实现service方法
    • 不能重写Init(ServletConfig config)方法,因为会覆盖原方法,从而无法得到内部的ServletConfig对象
    • 但可以重写Init()方法。Init()方法是在GenericServlet类中定义的方法,Init(ServletConfig config)方法调用了Init()方法。
    public abstract class GenericServlet implements Servlet, ServletConfig, Serializable{
      ...
    private
    transient ServletConfig config;

    //GenericServlet类中的Init方法

    public
    void init(ServletConfig config) throws ServletException{ this.config = config; init(); } public void init() throws ServletException{}
    public abstract void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse) throws ServletException, IOException;
      ...
    }

    ServletDemo2类

    继承GenericServlet类

    //通过继承GenericServlet类实现 Servlet开发
    public class ServletDemo2 extends GenericServlet {
    
      @Override
      public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
          response.getWriter().write("hello GenericServlet");
          //直接往浏览器输出
      }
    }

    配置和映射Servlet

    <servlet>
    <servlet-name>ServletDemo2</servlet-name>
    <servlet-class>cn.itcast.servlet.demo.ServletDemo2</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ServletDemo2</servlet-name>
    <url-pattern>/servletdemo2</url-pattern>
    </servlet-mapping>

    第三种:继承抽象类 HttpServlet

    HttpServlet类原理

    HttpServlet类继承了GenericServlet类

    并在servlet(ServletRequest request, ServletResponse response)中获得其HttpServletRequest和HttpServletResponse对象

    且根据getMethod方法获得了数据传输方式,根据传输方式的不同调用了不同的方法(doGet、doPost等)

    所以只需重写doGet、doPost等方法就行了

    public abstract class HttpServlet extends GenericServlet{
    public
    void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException{

    HttpServletRequest request;
    HttpServletResponse response;
    try{ request = (HttpServletRequest)req; response = (HttpServletResponse)res; } catch (ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
    protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException{
    String method = req.getMethod();
    if (method.equals("GET")) {
    ...
    doGet(req, resp);
    ...
    }
    else if (method.equals("POST")) {
    doPost(req, resp);
    }
    ...
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException{
    ...
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException{
    ...
    }
    }

    ServletDemo3类

    继承HttpServlet类

    //通过继承HttpServlet 开发Servlet
    //最常用的
    public class ServletDemo3 extends HttpServlet {
        //处理get请求
        //request用于获取客户端(浏览器)的信息
        //response用于向客户端(浏览器)返回信息 @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } //处理post请求
        //request用于获取客户端(浏览器)的信息
        //response用于向客户端(浏览器)返回信息 @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8");//设置编码 PrintWriter pw=response.getWriter(); pw.write("第三种继承HttpServlet");//输出 }
    }

    配置和映射Servlet

    <servlet>
    <servlet-name>ServletDemo3</servlet-name>
    <servlet-class>cn.itcast.servlet.demo.ServletDemo3</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ServletDemo3</servlet-name>
    <url-pattern>/servletdemo3</url-pattern>
    </servlet-mapping>
  • 相关阅读:
    微信小程序HTTPS
    微信商城-1简介
    va_list
    Event log c++ sample.
    EVENT LOGGING
    Analyze Program Runtime Stack
    unknow table alarmtemp error when drop database (mysql)
    This application has request the Runtime to terminate it in an unusual way.
    How to check if Visual Studio 2005 SP1 is installed
    SetUnhandledExceptionFilter
  • 原文地址:https://www.cnblogs.com/CComma/p/7106773.html
Copyright © 2020-2023  润新知