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

  • 相关阅读:
    使用pymouse模块时候报错No module named 'windows'
    解决PIL透明的图片放在新图片上报错
    解决PIL切圆形图片存在锯齿
    常见金融术语-帮助更好的理解金融业务需求
    FastJson序列化时过滤字段(属性)的方法总结
    数据库事务4种隔离级别及7种传播行为
    硬件网络接口规范
    「题解」P5906 【模板】回滚莫队&不删除莫队
    「学习笔记」优美的暴力——莫队
    2017 NOIp提高组 DAY2 试做
  • 原文地址:https://www.cnblogs.com/nongzihong/p/10166470.html
Copyright © 2011-2022 走看看