본문 바로가기

JSP

JSP 컨트롤러(Controller) properties,XML 적용

반응형
package com.javalec.ex.frontcontroller;

import java.io.IOException;
..생략..

public class BFrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public BFrontController() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet");
		actionDo(request, response);
	}
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doPost");
		actionDo(request, response);
	}
	
	private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("EUC-KR");
		
		String viewPage = null;
		BCommand command = null;
		
		String uri = request.getRequestURI();
		String conPath = request.getContextPath();
		String com = uri.substring(conPath.length());
		
		if(com.equals("/write_view.do")) {
			viewPage = "write_view.jsp";
		} else if(com.equals("/write.do")) {
			command = new BWriteCommand();
			command.execute(request, response);
			viewPage = "list.do";
		} else if(com.equals("/list.do")) {
			command = new BListCommand();
			command.execute(request, response);
			viewPage = "list.jsp";
		} else if(com.equals("/content_view.do")){
			command = new BContentCommand();
			command.execute(request, response);
			viewPage = "content_view.jsp";
		} else if(com.equals("/modify.do")) {
			command = new BModifyCommand();
			command.execute(request, response);
			viewPage = "list.do";
		} else if(com.equals("/delete.do")) {
			command = new BDeleteCommand();
			command.execute(request, response);
			viewPage = "list.do";
		} else if(com.equals("/reply_view.do")) {
			command = new BReplyViewCommand();
			command.execute(request, response);
			viewPage = "reply_view.jsp";
		} else if(com.equals("/reply.do")) {
			command = new BReplyCommand();
			command.execute(request, response);
			viewPage = "list.do";
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
		dispatcher.forward(request, response);
		
	}
}

시작하기에 앞서 JSP 개발할 때 JSP에서 온 URL요청을 분류해서 처리할 때는 위와 같은 식으로 처리를 할 수도 있다.

하지만 이런 식으로 하면 유지보수에 좋지 않고, 눈으로 보기에도 복잡하고 가독성이 떨어진다 그래서 소개할 방식은  두 가지가 있는데 첫 번째는 바로 Properties 파일을 이용하는 것이고, 두 번째는 XML 파일을 이용하는 것이다.

Properties 파일

#board controller
/file.bo=com.si.var.command.BFilecommand
/list.bo=com.si.var.command.BListcommand
/write.bo=com.si.var.command.BWritecommand
/view.bo=com.si.var.command.BViewcommand
/reply.bo=com.si.var.command.BReplycommand
/reReply.bo=com.si.var.command.BReReplycommand
#user controller
/idCheck.bo=com.si.var.command.UIDCheckcommand
/JoinUser.bo=com.si.var.command.UJoincommand
/Login.bo=com.si.var.command.ULogincommand
/Logout.bo=com.si.var.command.ULogoutcommand

위처럼 Properties 파일은 맵처럼 키(KEY)와 밸류(Value)로 저장이 된다. 이제 이 파일을 읽어서 간단하게 처리해주면 끝.

package dispatch;

import java.io.*;
..생략..

@WebServlet("*.c3")	
public class Dispatch extends HttpServlet {
	
	public HashMap map;	// 등록된 결과 기억할 변수
	
	public void init(ServletConfig config) throws ServletException {
		Properties prop = new Properties();
		try {
			// 파일을 스트림으로 만들고
			String path = this.getClass().getResource("/").getPath();
			path = path + "resources/c3.properties";
			File file = new File(path);
			FileInputStream fin = new FileInputStream(file);
			// 읽고
			prop.load(fin);
			// 지금 상태는 파일의 내용을 읽어서 맵으로 만들어 놓은 상태다.
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		/*
				prop에는 데이터가 문자열로 저장이 되어 있다.
				그래서 지금은 실행이 불가능하다.
				실행가능한 클래스로 다시 만들어서 Map에 넣어줘야 한다.
				
				방법]
					prop에 들어있는 내용을 꺼내서
					실행 가능한 클래스로 만든후
					이것을 Map에 넣어준다.
					
				먼저 prop에 들어있는 값을 꺼낼려면 key 값이 필요하다.
				일단 key값만 모두 꺼내고
				이후 데이터를 꺼낸후 실행가능한 클래스로 만들고
				Map에 넣어주면 된다.
		 */
		map = new HashMap();
		
		Enumeration en = prop.keys();
		while(en.hasMoreElements()) {
			// 키값을 하나씩 꺼내서
			String key = (String) en.nextElement();
			// 키값에 해당하는 클래스이름을 얻고
			String strClass = prop.getProperty(key);
			// 이것을 실행가능한 클래스로 만들고
			try {
				// 문자열을 실제 클래스로 변환해주고
				Class tmp = Class.forName(strClass);
				// 강제로 new 시켜놓고
				Object o = tmp.newInstance();
				map.put(key, o);
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public void service(HttpServletRequest req, HttpServletResponse resp) {
		// 이 함수는 요청이 들어오면 실행되는 함수
		// 따라서 디스패치 서블릿의 목적에 맞게 요청을 분석하고
		
		// 1. 전체 요청을 알아내고
		String full = req.getRequestURI();
		// 2. 도메인 알아내고 길이 알아내고
		String domain = req.getContextPath();
		int len = domain.length();
		String real = full.substring(len);
		
		// 원하는 컨트롤러를 선택해서
		// 위에서 만들어 놓은 map에서 뽑아내면 된다.
		MainController controller = (MainController) map.get(real);
		
		// 뷰를 반환받고 (executeC3() 실행해서 <== MainController.executeC3() 를 오버라이드한 함수이므로...)
		req.setAttribute("isRDR", 0);
		String view = controller.executeC3(req, resp);
		int rdr = (int) req.getAttribute("isRDR");
		if(rdr == 1) {
			try {
				resp.sendRedirect(view);
			} catch(Exception e) {
				e.printStackTrace();
			}
			return;
		}
		// 뷰를 호출한다.
		try {
			RequestDispatcher rd = req.getRequestDispatcher(view);
			rd.forward(req, resp);
		}catch(Exception e) {}
	}
	
}

 이 방법을 쓴다면 유지 보수에도 용이해지고, 추가하고 싶은 것은 Properties에 한 줄만 추가해주면 끝

눈에 보기에도 정말 좋다. 

다음은 XML파일을 사용한 것이다.

XML 파일

<?xml version="1.0" encoding="UTF-8"?>

<Testxml>
	<key>/file.bo</key>
	<value>com.si.var.command.BFilecommand</value>
	<key>/list.bo</key>
	<value>com.si.var.command.BListcommand</value>
	<key>/write.bo</key>
	<value>com.si.var.command.BWritecommand</value>
	<key>/view.bo</key>
	<value>com.si.var.command.BViewcommand</value>
	<key>/reply.bo</key>
	<value>com.si.var.command.BReplycommand</value>
	<key>/reReply.bo</key>
	<value>com.si.var.command.BReReplycommand</value>
	<key>/idCheck.bo</key>
	<value>com.si.var.command.UIDCheckcommand</value>
	<key>/JoinUser.bo</key>
	<value>com.si.var.command.UJoincommand</value>
	<key>/Login.bo</key>
	<value>com.si.var.command.ULogincommand</value>
	<key>/Logout.bo</key>
	<value>com.si.var.command.ULogoutcommand</value>
</Testxml>

 

@WebServlet("*.bo")	
public class UController extends HttpServlet {
	
	public HashMap map;	
	public ArrayList<String> key;
	public ArrayList value;
	public void init() throws ServletException {
		System.err.println("init!!!!");
		try {
			// DOM Parser 사용해보기~~
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = doc = builder.parse("path\\Test.xml");
			
			NodeList list = doc.getElementsByTagName("Testxml");
			
			key = new ArrayList<String>();
			value = new ArrayList();
			for(Node node= list.item(0).getFirstChild() ; node !=null ; node=node.getNextSibling()) {
				if(node.getNodeName().equals("key")) {
					key.add(node.getTextContent());
				}else if(node.getNodeName().equals("value")) {
					value.add(node.getTextContent());
				}
			}
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		map = new HashMap();
		for(int i = 0; i < key.size(); i++) {
			String strClass = (String) value.get(i);
			try {
				Class tmp = Class.forName(strClass);
				Object o = tmp.newInstance();
				map.put(key.get(i), o);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		
	}

이 방법은 위의 properties 파일 사용 방식과 매우 유사하다. DOM xmlParser를 사용해서 xml파일을 파싱 한다. Dom방식 말고 Sax방식도 있다. 하지만 구현 방식이 dom방식이 편하기 때문에 dom방식을 선택했다. 

각각 key와 value 리스트에 넣어서 map에 key와 value로 넣는다 그 이후는 service에서 똑같이 해주면 된다

방법의 차이여서 아무거나 사용해도 된다 이것 말고도 많은 방법이 있겠지만 스프링을 사용하자

 

반응형

'JSP' 카테고리의 다른 글

JSP 게시판 만들기(2) MVC패턴 model2  (0) 2019.07.01
JSP 게시판 만들기(1) MVC패턴 model2  (0) 2019.06.30