ServletContext 매개변수는 웹 어플리케이션 전역에서 사용할수 있다.
선언
1 2 3 4 5 6 | <web-app> <context-param> <param-name>contextParam</param-name> <param-value>paramtest</param-value> </context-param> </web-app> | cs |
사용방법
1 2 3 | ServletContext context = this.getServletContext(); String admin = context.getInitParameter("contextParam"); System.out.println(admin); | cs |
ServletContext 타입 변수를 선언하고 서블릿 클래스가 상속받은클래스인
HttpServlet 로부터 상속받은 getServletContext() 메서드를통해 생성한다.
ServletContext 타입의 객체가 가지고있는 getInitParameter(); 메서드를 통해
Context에 저장되어 있는 변수를 얻어올수 있다.
ServletConfig 매개변수는 변수가 선언된 해당 서블릿에서 사용할수 있다.
선언
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <web-app> 서블릿에서의 선언 <servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>com.servlets.TestServlet</servlet-class> <init-param> <param-name>test</param-name> <param-value>test</param-value> </init-param> </servlet> 필터에서의 선언 <filter> <filter-name>Filter</filter-name> <filter-class>com.filters.FilterTest</filter-class> <init-param> <param-name>test</param-name> <param-value>test</param-value> </init-param> </filter> </wev-app> | cs |
서블릿에서의 사용방법
1 | String test = getInitParameter("test"); | cs |
서블릿에서는 서블릿이 GenericServlet를 상속받는클래스이므로
getInitParameter(); 메서드를 메서드의 이름만으로 호출이 가능하다.
필터에서의 사용방법
필터에서 사용할 때는 클래스의 멤버변수로 FilterConfig 타입 변수를 선언하고
init메서드를 통해 매개변수로 들어온 config를 멤버변수에 대입한다.
1 2 3 4 5 6 7 8 | public class CharacterEncodingFilter implements Filter{ FilterConfig config; @Override public void init(FilterConfig config) throws ServletException { this.config = config; } } | cs |
FilterConfig타입 참조변수의 getInitParameter() 메서드를 통해 값을 얻는다.
1 | String test = config.getInitParameter("test"); | cs |
'JSP&Servlet' 카테고리의 다른 글
커넥션 풀 (0) | 2017.02.26 |
---|---|
이벤트 리스너(event listener) (0) | 2017.02.26 |
필터 (0) | 2017.02.26 |
ServletContext 객체 (0) | 2017.02.26 |
서블릿의 초기화 파라미터 / init-param (0) | 2017.02.26 |