접기
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance " xmlns="http://java.sun.com/xml/ns/javaee " xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd " xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd " id="WebApp_ID" version="2.5"> <context-param> <param-name>name</param-name> <param-value>홍길동</param-value> </context-param> <context-param> <param-name>email</param-name> <param-value>abc@abc.com</param-value> </context-param> <context-param> <param-name>phone number</param-name> <param-value>010-111-2222</param-value> </context-param>
<servlet>
<servlet-name>ContextParamServlet</servlet-name>
<servlet-class>servlet.initparam.ContextParamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextParamServlet</servlet-name>
<url-pattern>/ContextParamServlet</url-pattern>
</servlet-mapping>
</web-app>
접기
접기
package servlet.initparam;
import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/** * Servlet implementation class ContextParamServlet */ public class ContextParamServlet extends HttpServlet { private static final long serialVersionUID = 1L; public ContextParamServlet() { super();
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //ServletContext를 이용해 Context level의 초기 파라미터 조회 //1. ServletContext객체 조회 ServletContext ctx = getServletContext(); //2. 초기 파라미터 조회 String name = ctx.getInitParameter("name"); String email = ctx.getInitParameter("email"); String phoneNumber = ctx.getInitParameter("phone number"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("이름 : "+name+"<br>"); out.println("email : "+email+"<br>"); out.println("전화번호 : "+phoneNumber+"<br>"); out.println("</body></html>"); }
}
접기
수정되는 것을 볼 수 있다.
* 기존 GreetingServlet에 ContextParamServlet의 선언부와 실행하는 것을 넣어주면 어디서든 xml에서 넣은 값을 가져다가 사용할 수 있다. (이것이 이전장에서 말한 servlet내의 xml에 ContextParam객체에 다 접근가능 하다는 것을 보여준다.)