다양한 관심 :)

Java - servlet( 서블릿 ) 컨텍스트 초기화 파라미터 본문

프로그래밍 공부/JAVA

Java - servlet( 서블릿 ) 컨텍스트 초기화 파라미터

뚜뚜:) 2020. 11. 28. 07:25

 컨텍스트 초기화 파라미터

  • 웹 애플리케이션 전체에 속하는 초기화 파라미터 
  • <context-param> 으로 작성한다
  • 이 <context-param>요소는 <param-name>, <param-value>의 자식 요소가 있다.
  • Servlet 클래스에서는 getServletContext()메서드를 이용해서 ServletContext객체를 구하고,
    이 객체의 getInitParameter( ) 메서드를 호출하여 사용한다.  -> 형식 ) getInitParameter("파라미터명"); 

web.xml - <context-param> 사용 

 
 <context-param>
    <param-name>myContext</param-name>
    <param-value>연습용 파라미터 값</param-value>
  </context-param>

 

ServletTest.class 

@WebServlet("/ServletTest.do")
public class ServletTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
   

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		ServletContext context = getServletContext();
		String param = context.getInitParameter("myContext");
		System.out.println(param);
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head><meta Charset='utf-8'>");
		out.println("<title>웹 서버의 정보 </title></head>");
		out.println("<body>");
		out.println("<h2>Context 초기화 파라미터</h2>");
		out.println("myContext : " + param + "<br>");
		out.println("</body>");
		out.println("</html>");
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}