#35 springboot: servlet container initializer

This commit is contained in:
haerong22
2023-03-03 00:21:20 +09:00
parent 5c1adfbe5a
commit ffbe50b5dc
6 changed files with 86 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
package hello.container;
import jakarta.servlet.ServletContext;
public interface AppInit {
void onStartup(ServletContext servletContext);
}

View File

@@ -0,0 +1,18 @@
package hello.container;
import hello.servlet.HelloServlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRegistration;
public class AppInitV1Servlet implements AppInit {
@Override
public void onStartup(ServletContext servletContext) {
System.out.println("AppInitV1Servlet.onStartup");
// 서블릿 코드 등록
ServletRegistration.Dynamic helloServlet =
servletContext.addServlet("helloServlet", new HelloServlet());
helloServlet.addMapping("/hello-servlet");
}
}

View File

@@ -0,0 +1,16 @@
package hello.container;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import java.util.Set;
public class MyContainerInitV1 implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
System.out.println("MyContainer.onStartup");
System.out.println("c = " + c);
System.out.println("ctx = " + ctx);
}
}

View File

@@ -0,0 +1,27 @@
package hello.container;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.HandlesTypes;
import java.util.Set;
@HandlesTypes(AppInit.class)
public class MyContainerInitV2 implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
System.out.println("MyContainerInitV2.onStartup");
System.out.println("c = " + c);
for (Class<?> appInitClass : c) {
try {
AppInit appInit = (AppInit) appInitClass.getDeclaredConstructor().newInstance();
appInit.onStartup(ctx);
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}

View File

@@ -0,0 +1,16 @@
package hello.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("HelloServlet.service");
resp.getWriter().println("hello servlet!");
}
}

View File

@@ -0,0 +1,2 @@
hello.container.MyContainerInitV1
hello.container.MyContainerInitV2