zoukankan      html  css  js  c++  java
  • 使用 java替换web项目的web.xml

    创建一个接口:

    package my.web;
    
    public interface SpringWeb {
        void config();
    }

    实现类:

    package my;
    
    import my.web.SpringWeb;
    
    public class SpringInit implements SpringWeb {
        @Override
        public void config() {
            System.out.println("大家好");
        }
    }
    import my.web.SpringWeb;
    
    public class SpringWeblnitializer implements SpringWeb {
        @Override
        public void config() {
            System.out.println("你好,哈皮!");
        }
    }

    创建:MyWebConfig 等同于web.xml

    package my.web;
    
    import javax.servlet.ServletContainerInitializer;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.HandlesTypes;
    import java.util.Set;
    
    
    // 等同于web.xml文件
    @HandlesTypes({SpringWeb.class})
    public class MyWebConfig implements ServletContainerInitializer {
        @Override
        public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
            System.out.println("hello wrold");
    
            for (Class<?> aclass : set) {
                SpringWeb o = null;
                try{
                    o = (SpringWeb) aclass.newInstance();
                    o.config();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }

    创建一个servlet 继承于 HttpServlet

    package my.web;
    
    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.PrintWriter;
    
    @WebServlet("/aaa")
    public class MyServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("。。。。。");
        }
    }
    

      

     在src下创建 META-INF 包 

    其次在创建一个 services 的包  添加一个filed的文件

    //加上这一句 目的项目在初始化自动找到web.xml文件
    my.web.MyWebConfig

    结果:

    源码地址:https://github.com/nongzihong/servlet_new

  • 相关阅读:
    HTTP 状态码大全
    Redis Cluster数据分片机制
    redis 哨兵集群原理及部署
    python 连接 redis cluster 集群
    python连接redis哨兵集群
    Ubuntu设置终端操作行为的回收站
    实用Golang库
    实用的Python库
    Python 生成 JWT(json web token) 及 解析方式
    django 进行语言的国际化及在后台进行中英文切换
  • 原文地址:https://www.cnblogs.com/nongzihong/p/10166470.html
Copyright © 2011-2022 走看看