Spring
14. 관심사의 분리와 MVC패턴/원리(2) - 패스트캠퍼스 백엔드 부트캠프 3기
gkss2tpt
2025. 2. 3. 09:31
1.
2.
- txtView1.txt
id:${id}
pwd:${pwd}
- txtView2.txt
id=${id}, pwd=${pwd}
- MethodCall
public class MethodCall {
public static void main(String[] args) throws Exception{
HashMap map = new HashMap();
System.out.println("before:"+map);
ModelController mc = new ModelController();
String viewName = mc.main(map);
System.out.println("after :"+map);
render(map, viewName);
}
static void render(HashMap map, String viewName) throws IOException{
String result = "";
// 1. 뷰의 내용을 한줄씩 읽어서 하나의 문자열로 만든다.
Scanner sc = new Scanner(new File(viewName+".txt"));
while(sc.hasNextLine()) {
result += sc.nextLine()+ System.lineSeparator();
}
// 2.map에 담긴 key를 하나씩 읽어서 template의 $(key)를 value바꾼다.
Iterator it = map.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
// 3. replace()로 key를 value 치환한다.
result = result.replace("${"+key+"}", (String)map.get(key));
}
// 4. 렌더링 결과를 출력한다.
System.out.println(result);
}
}
class ModelController{
public String main(HashMap map) {
// 작업 결과를 map에 저장
map.put("id", "asdf");
map.put("pwd", "1111");
return "txtView2"; // 뷰이름 반환
}
}
- 결과(txtView2.txt)
before:{}
after :{id=asdf, pwd=1111}
id=asdf, pwd=1111
- 결과(txtView1.txt)
before:{}
after :{id=asdf, pwd=1111}
id:asdf
pwd:1111