웹 : 서블릿과 템플릿, model1과 model2 차이 : 0223
<context-param></context-param> (application자체에 파라미터를 줄 수 있는 것, web.xml에서 사용)
web.xml에 context-param을 설정해두면 등록된 서블릿들은 모두 그 param을 사용할 수 있어
다시 빌드하지 않아도 된다.
이렇게 하는 이유??
서블릿은 싱글톤으로 사용되는데,
싱글톤에서는 전역변수 사용이 위험할 수 있다. 그래서 web.xml에 등록하고 사용한다는것....!
servlet(+jsp)
(servlet과 jsp를 나누지 않는다면?)
단점 : "S"OLID = 단일 책임의 원칙
디자이너와 개발자의 협업이 힘들다.
변경되는 코드와 그렇지 않은 코드를 분리해야한다.
↓↓↓
서블릿 컨텍스트로 톰캣과 대화할 수 있다. = 톰캣의 정보를 받아올 수 있다.(getServletContext)
application.getRealPath(servletPath) = > 논리주소주면 물리주소 줄게.
template
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
input{
background-color: red;
}
</style>
</head>
<body>
<form action="<%=cPath %>/image.do">
<select name="name">
<%=options %>
</select>
<input type="submit" value="전송">
</form>
</body>
</html>
=> 일단, 템플릿에 구멍을 뚫었다. <%= > 표현식 사용!
-------------------------------------------------------------------------------
public class L306SampleServlet extends HttpServlet{
private ServletContext application;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
application = getServletContext();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String servletPath = req.getServletPath();
System.out.println(servletPath);
String realPath = application.getRealPath(servletPath); //논리주소 주면 물리주소 줄게.
System.out.println(realPath);
String template = Files.readAllLines(Paths.get(realPath))
.stream()
.collect(Collectors.joining("\n"));
String contents = template.replace("<%=time %>", new Date().toString());
try(
PrintWriter out = resp.getWriter();
){
out.print(contents);
}
}
}
사용순서
1.템플릿을 읽는다.
2.템플릿의 구멍을 찾는다.(구멍내는 일정 규칙이 있다.) 구멍의 네임을 찾는다.
3. 응답데이터로 내보낸다.
단점
1. 매번 서블릿과 뷰를 둘다 만들어야한다.
2. 구멍이 조금만 수정되도 데이터가 안들어간다.
<%=option %> ==> <%=option%> : 띄어쓰기 때문에 표현식 찾기에 실패한다.
3.(model1, model2 ==> 책임이 분리되어 있는가의 차이)
PrintWriter out = resp.getWriter();
여기서 응답이 나갔다. 결국엔 여기도 모델1방식...
model1과 model2 차이
==>. 책임이 분리되어 있는가
< request > 와
< response > 의 책임이 분리되어 있다.
controller
1. 요청을 받는다. 2. 데이터를 만든다. 3. forward를 부른다.
view(template 엔진)
1. 데이터를 꺼낸다. 2. 컨텐츠를 만든다. 3. 출력(응답)한다.
model2 방법을 더 배워보자!