码迷,mamicode.com
首页 > 编程语言 > 详细

使用 java替换web项目的web.xml

时间:2018-12-24 02:57:05      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:protect   initial   ali   nts   etc   types   这一   web.xml   writer   

 

 

创建一个接口:

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

 

使用 java替换web项目的web.xml

标签:protect   initial   ali   nts   etc   types   这一   web.xml   writer   

原文地址:https://www.cnblogs.com/nongzihong/p/10166470.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!