http://noritersand.tistory.com/129
ServletConfig, ServletContext
web.xml 문서를 조작하여 서블릿에 정보를 전달하기 위한 용도로 사용되는 인터페이스.
특징과 설정방법은 다음과 같다 :
구 분 | 적용 | 범위 설정 |
ServletConfig |
| <servlet> <servlet-name> </servlet-name> <servlet-class> </servlet-class> <init-param> <param-name> </param-name> <param-value> </param-value> </init-param> </servlet> |
ServletContext | 동일 웹 애플리케이션 내 모든 서블릿(또는 JSP)에서 사용 할 수 있다. | <context-param> <param-name> </param-name> <param-value> </param-value> </context-param> |
만약 서버의 설정을 변경해야 할 때라고 치자.
해당 값이 자바파일에 명시되어 있다면 그 클래스를 수정하여 다시 컴파일하고 배포도 다시 해야한다.
하지만 ServletConfig나 ServletContext 인터페이스를 이용해 작성하면 xml 수정 후 서버만 리셋하면 된다.
어느것이 더 편한지는 개발자 쓰기 나름
MVC2 패턴 구현에도 사용되는 듯 하다. 바로가기
● 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | < servlet > < servlet-name >test</ servlet-name > < servlet-class >com.test1.TestServlet</ servlet-class > < init-param > < param-name >name</ param-name > < param-value >han</ param-value > </ init-param > < init-param > < param-name >age</ param-name > < param-value >20</ param-value > </ init-param > </ servlet > < servlet-mapping > < servlet-name >test</ servlet-name > < url-pattern >/test</ url-pattern > </ servlet-mapping > < context-param > < param-name >city</ param-name > < param-value >seoul</ param-value > </ context-param > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletConfig config = getServletConfig(); //해당 서블릿에서만 사용가능 ServletContext context = getServletContext(); //동일한 웹어플리케이션 어디서든 접근가능 String name = config.getInitParameter( "name" ); String age = config.getInitParameter( "age" ); String city = context.getInitParameter( "city" ); //로그설정 context.log( "로그를 출력합니드아" ); resp.setContentType( "text/html;charset=utf-8" ); PrintWriter out = resp.getWriter(); out.print( "name:" + name + "<br/>" ); out.print( "age:" + age + "<br/>" ); out.print( "city:" + city + "<br/>" ); } |
http://noritersand.tistory.com/65#j_3
servlet MVC2 구현예제
목차
config.properties
web.xml
CONTROL
MODEL
VIEW
WebContent/WEB-INF/config.properties
/bbs.do=com.mvc.bbs.BoardAction
/guest.do=com.mvc.guest.GuestAction
WebContent/WEB-INF/web.xml
1 2 3 4 5 6 7 8 | < servlet > < servlet-name >my</ servlet-name > < servlet-class >com.mvc.MyServlet</ servlet-class > < init-param > < param-name >config</ param-name > < param-value >/WEB-INF/config.properties</ param-value > </ init-param > </ servlet > |
CONTROL
● com.mvc.MyServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | public class MyServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Map<String, Object> map = new Hashtable<String, Object>(); public void init(ServletConfig config) throws ServletException { super .init(config); ServletContext context = getServletContext(); // web.xml 의 servlet 태그안의 init-param 값 읽어오기 String pathname = config.getInitParameter( "config" ); if (pathname == null ) return ; pathname = context.getRealPath(pathname); try { // properties 파일에 저장된 내용을 Properties 객체에 저장 Properties prop = new Properties(); FileInputStream fis = null ; fis = new FileInputStream(pathname); // 파일의 내용을 읽어 Properties 객체에 저장 prop.load(fis); fis.close(); // Properties 객체에 저장된 클래스의 객체를 생성 map에 저장 Iterator<Object> it = prop.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String className = prop.getProperty(key); Class<?> cls = Class.forName(className); Object ob = cls.newInstance(); map.put(key, ob); } } catch (Exception e) { System.out.println(e); } } public void destroy() { } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { MyAction action = null ; try { String uri = req.getRequestURI(); if (uri.indexOf(req.getContextPath()) == 0 ) { uri = uri.substring(req.getContextPath().length()); action = (MyAction) map.get(uri); action.execute(req, resp); } } catch (Exception e) { System.out.println(e); } } } |
MODEL
● com.mvc.MyAction.java
1 2 3 4 5 6 7 8 9 10 11 12 | public abstract class MyAction { public abstract void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; public void forward(HttpServletRequest req, HttpServletResponse resp, String path) throws ServletException, IOException { RequestDispatcher rd = req.getRequestDispatcher(path); rd.forward(req, resp); } } |
● com.mvc.BoardAction.java
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class BoardAction extends MyAction { public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String mode = req.getParameter( "mode" ); if (mode == null || mode.equals( "list" )) { forward(req, resp, "/mvc/bbs/list.jsp" ); } else if (mode.equals( "created" )) { forward(req, resp, "/mvc/bbs/created.jsp" ); } } } |
● com.mvc.GuestAction.java
1 2 3 4 5 6 7 8 9 10 11 12 | public class GuestAction extends MyAction { public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String mode = req.getParameter( "mode" ); if (mode == null || mode.equals( "guest" )) { forward(req, resp, "/mvc/guest/guest.jsp" ); } } } |
VIEW
● root/mvc/bbs/list.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | < body > < a href="<%=cp%>/bbs.do">게시판</ a > < a href="<%=cp%>/guest.do">방명록</ a >< br /> 게시판 리스트입니다.< br /> < a href="<%=cp%>/bbs.do?mode=created">글쓰기</ a > </ body > root/mvc/bbs/created.jsp < body > < a href="<%=cp%>/bbs.do">게시판</ a > < a href="<%=cp%>/guest.do">방명록</ a >< br /> 게시판 글쓰기입니다.< br /> </ body > |
● root/mvc/guest/guest.jsp
1 2 3 4 5 6 7 | < body > < a href="<%=cp%>/bbs.do">게시판</ a > < a href="<%=cp%>/guest.do">방명록</ a >< br /> 방명록입니다.< br /> </ body > |
반응형
'차근차근 > JAVA JSP' 카테고리의 다른 글
향상된 For문 [ for(:)] (0) | 2014.08.28 |
---|---|
init (0) | 2014.08.24 |
[JAVA] serialVersionUID 이란? Warning 해결하기 (0) | 2014.08.24 |
자바 디자인 패턴 1 - Iterator (0) | 2014.08.20 |
무작정 자료 수집 (1) | 2014.07.30 |