Java Web Development Workbook Chapter. 05
MVC 구조 (웹 애플리케이션)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="Lesson05.Member" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
...
<%
if (member.getEmail() != null) {
%>
<%=member.getName()%>
<a style="color:white;"
href="<%=request.getContextPath()%>/auth/logout">Logout</a>
<%
}
%>
...
<%!
private String calculate(int a, int b, String op) {
int r = 0;
if ("+".equals(op)) {
r = a + b;
}
else if ("-".equals(op)) {
r = a - b;
}
else if ("*".equals(op)) {
r = a * b;
}
else if ("/".equals(op)) {
r = a / b;
}
return Integer.toString(r);
}
%>
request, response, pageContext, session, application, config, out, page, exception
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher(
"/Lesson05/MemberAdd.jsp"
);
rd.include(request, response);
}
HttpServletRequest 로부터 얻음
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
웹 애플리케이션이 시작하거나 종료할 때 발생 -> 서블릿 컨테이너는 javax.servlet.ServletContextListener 의 메소드 호출
MemberDao memberDao = new MemberDao();
memberDao.setConnection((Connection) sc.getAttribute("conn"));
Member member = new Member()
.setEmail(request.getParameter("email"))
.setPassword(request.getParameter("password"))
.setName(request.getParameter("name"));
int result = memberDao.insert(member);
서블릿이 요청을 처리할 때마다 매번 DAO 인스턴스를 생성 -> 많은 garbage가 생성, 실행 시간이 길어짐.
서블릿 간의 공유: 여러 서블릿이 사용하는 객체를 ServletContext에 저장
@WebListener
public class ContextLoaderListener implements ServletContextListener {
private Connection conn;
@Override
public void contextInitialized(ServletContextEvent event) {
try {
ServletContext sc = event.getServletContext();
Class.forName(sc.getInitParameter("driver"));
conn = DriverManager.getConnection(
sc.getInitParameter("url"),
sc.getInitParameter("username"),
sc.getInitParameter("password")
);
MemberDao memberDao = new MemberDao();
memberDao.setConnection(conn);
sc.setAttribute("memberDao", memberDao);
}
catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent event) {
try {
conn.close();
} catch (Exception e) {
}
}
}
풀링: 자주 쓰는 객체를 미리 만둘어두고, 필요할 때마다 꺼내 쓰고 반납하는 방식
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
[ch05] 5.13. Used BasicDataSource.
JNDI Name | Resource |
---|---|
java:comp/env | 응용 프로그램 환경 항목 |
java:comp/env/jdbc | JDBC DataSource |
java:comp/ejb | EJB 컴포넌트 |
java:comp/UserTransaction | UserTransaction 객체 |
java:comp/env/mail | JavaMail 연결 객체 |
java:comp/env/url | URL 정보 |
java:comp/env/jms | JMS 연결 객체 |
<!-- Context.xml -->
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource
name="jdbc/studydb" // JNDI name
auth="Container" // The author of resource
type="javax.sql.DataSource" // The type of resource
maxActive="10" // Maximum connections.
maxIdle="3" // Maintaining not used connections.
maxWait="10000" // The wait time for preparing connection.
username="study" // user name.
password="study" // password.
driverClassName="com.mysql.jdbc.Driver" // JDBC driver class name.
url="jdbc:mysql://localhost/studydb" // DB connection url.
closeMethod="close" /> // close method name. When web application closed, it will invoked.
</Context>
<!-- web.xml -->
<resource-ref>
<res-ref-name>jdbc/studydb</res-ref-name> <!-- JNDI nae -->
<res-type>javax.sql.DataSource</res-type> <!-- Return type -->
<res-auth>Container</res-auth> <!-- Author of resource -->
</resource-ref>
// Get JNDI Resource.
InitialContext initialContext = new InitialContext();
DataSource dataSource = (DataSource)initialContext.lookup("java:comp/jdbc/studydb");
MemberDao memberDao = new MemberDao();
memberDao.setDataSource(dataSource);
...