使用 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

 

posted @ 2018-12-23 23:34  随★风  阅读(980)  评论(0编辑  收藏  举报