전 글은 여기 있습니다.
저번에는 Aware 인터페이스에 대해서 알아보았는데요
오늘은 ServletConfig와 Servlet 이 실행되는 환경인 ServletContext 부분을 알아볼 예정입니다
ServletConfig 인터페이스
이 인터페이스는 초기화 단계에서 서블릿에 대한 정보를 반환해 주는 인터페이스입니다.
public interface ServletConfig {
public String getServletName();
public ServletContext getServletContext();
public String getInitParameter(String name);
public Enumeration<String> getInitParameterNames();
}
servlet의 이름, servletContext 콘텍스트, 초기 파라미터, 초기 파라미터 이름과 같은 것들을 가져올 수 있습니다
ServletContext
서블릿이 실행되는 환경에 대한 정보를 가지고 있습니다.
JVM이나 WebApplication 당 하나만을 이용해 설정 정보를 공유합니다
다른 jvm 일 경우 공유되지 않기에, 전역 공유는 아니라 공유하는 목적으로 사용하는 것은 애매합니다
참고
public interface ServletContext {
public static final String TEMPDIR = "javax.servlet.context.tempdir";
public static final String ORDERED_LIBS = "javax.servlet.context.orderedLibs";
public String getContextPath();
public ServletContext getContext(String uripath);
public int getMajorVersion();
public int getMinorVersion();
public int getEffectiveMajorVersion();
public int getEffectiveMinorVersion();
}
가져올 수 있는 정보로 대표적인 것은 tomcat에서 웹상의 애플리케이션을 구분하기 위한 contextPath
환경변수 설정
한 jvm, 웹 애플리케이션에서 공유하기 위한 방식으로
public Object getAttribute(String name);
public void removeAttribute(String name);
public void setAttribute(String name, Object object);
이렇게 3가지 메서드가 있습니다
path로부터 정보를 가져오기
URI로부터 정보를 읽어 들이는 메서드로
public URL getResource(String path) throws MalformedURLException;
public InputStream getResourceAsStream(String path);
이런 것들이 있습니다
추가적으로 특정 자원에 접근했을 때, 다른 자원의 정보를 가져오는 Request Dispatcher
같은 것들도 가져올 수 있습니다
https://dololak.tistory.com/502
추가로 context 이기 때문에, servlet을 추가하는 기능도 있습니다
public ServletRegistration.Dynamic addServlet(String servletName, String className);
public <T extends Servlet> T createServlet(Class<T> c)
throws ServletException;
public ServletRegistration getServletRegistration(String servletName);
JSP 파일
public ServletRegistration.Dynamic addJspFile(String jspName, String jspFile);
JSP 파일이란 : Java Servlet Page의 약자로, html에 java code를 심는 것과 유사합니다
Thymleaf와 유사하다고 봐도 무방할 것 같습니다
https://yjh5369.tistory.com/entry/thymeleaf-vs-jsp
를 통해서 조금 더 자세하게 알 수 있습니다
필터
참고
https://kihwan95.tistory.com/6
간단하게 was에서 servlet 이나 controller에 요청이 가기 전에, 거치는 단계입니다.
필터를 관리하는 메서드로는
public FilterRegistration.Dynamic addFilter(String filterName, String className);
public <T extends Filter> T createFilter(Class<T> c) throws ServletException;
public FilterRegistration getFilterRegistration(String filterName);
이런 것들이 있습니다. 추가적으로 보시고 싶다면 ServletContext 쪽에서 확인하실 수 있습니다
세션
세션 관리를 위한 쿠키관리도 할 수 있는데요
public SessionCookieConfig getSessionCookieConfig();
public void setSessionTrackingModes(
Set<SessionTrackingMode> sessionTrackingModes);
public Set<SessionTrackingMode> getDefaultSessionTrackingModes();
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes();
이런 메서드를 통해서 session 관리나, 쿠키를 가져올 수 있습니다
session에 대한 설정을 다루는 메서드입니다
public int getSessionTimeout();
public void setSessionTimeout(int sessionTimeout);
리스너
public void addListener(String className);
public <T extends EventListener> T createListener(Class<T> c)
throws ServletException;
서블릿과 관련된 이벤트를 처리하기 위한 메서드들이 있습니다
대표적으로 ServletContextListener 가 Listener에 해당하는데요
public interface ServletContextListener extends EventListener {
/**
** Notification that the web application initialization process is starting.
* All ServletContextListeners are notified of context initialization before
* any filter or servlet in the web application is initialized.
* The default implementation is a NO-OP.
* @param sce Information about the ServletContext that was initialized
*/
public default void contextInitialized(ServletContextEvent sce) {
}
/**
** Notification that the servlet context is about to be shut down. All
* servlets and filters have been destroyed before any
* ServletContextListeners are notified of context destruction.
* The default implementation is a NO-OP.
* @param sce Information about the ServletContext that was destroyed
*/
public default void contextDestroyed(ServletContextEvent sce) {
}
}
이런 느낌으로 콘텍스트가 시작, 종료되었을 때의 이벤트를 받을 수 있습니다
참고 링크
그 외
현재 클래스 로더를 가져오는 getClassLoader();
public ClassLoader getClassLoader();
declareRoles로 servletContext의 role을 추가할 수 있습니다
public void declareRoles(String... roleNames);
호스트 이름도 가져올 수 있습니다
public String getVirtualServerName();
인코딩 정보에 대해서 처리할 수 있습니다
public String getRequestCharacterEncoding();
public void setRequestCharacterEncoding(String encoding);
public String getResponseCharacterEncoding();
public void setResponseCharacterEncoding(String encoding);
마무리
지금까지 servlet이 실행되는 환경인 ServletContext
servlet에 대한 기본 정보를 가져오는 ServletConfig에 대해서 알아보았습니다
servletContext에서는 정말 다양한 부분에 접근할 수 있는 환경이지만, 한 application(jvm) 단위로 돌아가기에 주의해야 합니다
'Spring' 카테고리의 다른 글
Test 의 db 롤백 어디까지 알아보셨나요? (1) | 2023.04.24 |
---|---|
DispatcherServlet 알아보기 - Servlet 편 (0) | 2023.04.22 |
DispatcherServlet 알아보기 - Aware 편 (6) | 2023.04.18 |
모든 객체를 스프링 빈으로 등록해도 괜찮나? (3) | 2023.04.14 |
잘못된 타입이 클라이언트로부터 왔을 때 커스텀 메시지 보여주기 (7) | 2023.03.06 |