티스토리 뷰

☠️ Java

java web-MVC & Oracle DataBase

James Wetzel 2024. 8. 29. 18:06
728x90
반응형

사전 정보

java version "21.0.4" 2024-07-16 LTS
Java(TM) SE Runtime Environment (build 21.0.4+8-LTS-274)
Java HotSpot(TM) 64-Bit Server VM (build 21.0.4+8-LTS-274, mixed mode, sharing)

 

Tomcat v10.1

 

 

추가 사항

java version "21.0.4" 에서 JSTL(Java Standard Tag Library)를 사용하기 위해

2개의 .jar 파일을 WEB-INF -> bin 폴더에 추가했다.

jakarta.servlet.jsp.jstl-api-2.0.0.jar
0.04MB
jakarta.servlet.jsp.jstl-2.0.0.jar
3.53MB

 

Oracle Database 연동을 위해 "ojdbc.jar" 파일을 WEB-INF -> bin 폴더에 추가했다.

ojdbc11.jar
6.87MB

 

jakarta.servlet.http.HttpServlet을 사용하기 위해 Tomcat v10.1에 있는 "servlet-api.jar"을

프로젝트 "Build Path"에 추가했다.

 

 

설정 사항

Tomcat -> context.xml

<Resource name="jdbc/myDataSource" 
            auth="Container"
            type="javax.sql.DataSource"
            driverClassName="oracle.jdbc.OracleDriver"
            url="jdbc:oracle:thin:@localhost:1521/xe"
            username="system"
            password="1234"
            maxTotal="20"
            maxIdle="10"
            maxWaitMillis="-1"/>

 

 

Code

MemberVO.java

package mvc.ex01;

import java.util.Date;

public class MemberVO {
	private String id;
	private String pwd;
	private String name;
	private String email;
	private Date joinDate;
	
	public MemberVO() {}
	public MemberVO(String id, String pwd, String name, String email, Date joinDate) {
		this.id = id;
		this.pwd = pwd;
		this.name = name;
		this.email = email;
		this.joinDate = joinDate;
	}
	
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	
	public String getPwd() {
		return this.pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	public String getName() {
		return this.name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getEmail() {
		return this.email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	public Date getJoinDate() {
		return this.joinDate;
	}
	public void setJoinDate(Date joinDate) {
		this.joinDate = joinDate;
	}

}

 

MemberDAO.java

package mvc.ex01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class MemberDAO {
	private DataSource dataSource;
	private Connection connection;
	private PreparedStatement preparedStatement;
	
	public MemberDAO() {
		try {
			// JNDI(Java Naming and Directory Interface) 선언
			Context context = new InitialContext();
			Context envContext = (Context)context.lookup("java:/comp/env");
			this.dataSource = (DataSource)envContext.lookup("jdbc/myDataSource");
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public List<MemberVO> memberList() {
		List<MemberVO> memberList = new ArrayList<MemberVO>();
		
		try {
			this.connection = this.dataSource.getConnection();
			
			String qury = "select * from t_member";
			this.preparedStatement = this.connection.prepareStatement(qury);
			
			ResultSet resultSet = this.preparedStatement.executeQuery();
			while(resultSet.next()) {
				MemberVO memberVO = new MemberVO(
						resultSet.getString("id"),
						resultSet.getString("pwd"),
						resultSet.getString("name"),
						resultSet.getString("email"),
						resultSet.getDate("joinDate")
				);
				
				memberList.add(memberVO);
			}
			
			resultSet.close();
			this.preparedStatement.close();
			this.connection.close();
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		
		return memberList;
	}
}

 

 

MemberController.java

package mvc.ex01;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Servlet implementation class MemberController
 */
@WebServlet("/member.do")
public class MemberController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public MemberController() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doHandle(request, response);
	}
	
	protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/htlm;charset=utf-8");
		
		List<MemberVO> memberList = new MemberDAO().memberList();
		request.setAttribute("memberList", memberList);
		
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("/memberlist.jsp");
		requestDispatcher.forward(request, response);
	}
}

 

 

memberlist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false"
    import="java.util.*, mvc.ex01.*"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>    
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<tr>
			<th>아이디</th>
			<th>비빌번호</th>
			<th>이름</th>
			<th>이메일</th>
			<th>가입일</th>
		</tr>
		<c:choose>
			<c:when test="${ !empty memberList }">
				<c:forEach var="member" items="${ memberList }">
					<tr>
						<td>${ member.id }</td>
						<td>${ member.pwd }</td>
						<td>${ member.name }</td>
						<td>${ member.email }</td>
						<td>${ member.joinDate }</td>
					</tr>
				</c:forEach>
			</c:when>
			<c:when test="${ empty memberList }">
				<tr>
					<td colspan="5">등록된 회원 정보가 없습니다.</td>
				</tr>
			</c:when>
		</c:choose>
	</table>
</body>
</html>

 

 

실행 흐름

1. 사용자는 "http://xxx.com/member.do" 를 호출한다.

2. MemberController.java 가 사용자 요청을 수신한다.(= Controller)

3. MemberController.java 는 MemberDAO.java 에 database 정보를 요청한다.(= Model)

4. MemberController.java 는 제공 받은 database 정보를 memberlist.jsp에 전달한다.(= View)

 

 

추가 정보

 

728x90
반응형