본문 바로가기

Programming/Java

자바 프로젝트 DB연결하기

반응형

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="board/list">list</a>
	<a href="board/write">write</a>
	<h1>Index Page</h1>
</body>
</html>

write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="<%=request.getContextPath() %>">HOME</a>
	<a href="list">list</a>
	<h1>This is writing Page</h1>
	
	<form action="write.nowon" method="post">
		<p>
			<input type="text" name="write" placeholder="Write">
		</p>
		<p>
			<input type="text" name="title" placeholder="Write Title">
		</p>
		<p>
			<textarea  name="content" rows="5" cols="100" placeholder="Write content"></textarea>
		</p>
		<p>
			<button type="submit">Writing done</button>
		</p>
	
	</form>
	
</body>
</html>

 

 

list.jsp

<%@page import="java.sql.Timestamp"%>
<%@ page import="java.sql.ResultSet" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%! 
ResultSet rs=null; 
%>
    
<%
rs = (ResultSet)request.getAttribute("list");
/* while(rs.next()){
	int no = rs.getInt("no");
	String title = rs.getString("title");
	int readCount = rs.getInt("read_count");
	String writer = rs.getString("writer");
	Timestamp createdDate = rs.getTimestamp("created_date");
	
	System.out.println("---------------"");
	System.out.println(no);
	System.out.println(title);
	System.out.println(readCount);
	System.out.println(writer);
	System.out.println(createdDate);
} */
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="<%=request.getContextPath() %>">HOME</a>
	<a href="write">Write</a>
	<table>
		<thead>
			<tr>
				<th>post number</th>
				<th>title</th>
				<th>read count</th>
				<th>writer</th>
				<th>created date</th>
			</tr>
		</thead>
		<tbody>
			<%
				if(rs==null){
			%>					
				<tr>
					<td colspan="5" style="text-align: center;">
					게시글이 존재하지 않습니다.
					</td>
				</tr>
			<%					
				}else{
					while(rs.next()){
			%>
				<tr>
					<td><%=rs.getInt("no") %></td>
					<td><%=rs.getString("title") %></td>
					<td><%=rs.getInt("read_count") %></td>
					<td><%=rs.getString("writer") %></td>
					<td><%=rs.getTimestamp("created_date") %></td>
				</tr>
			
			<%
					}
				} 
			%>
		</tbody>
	
	
	</table>
	
	<h1>This is list</h1>
</body>
</html>

 

write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="<%=request.getContextPath() %>">HOME</a>
	<a href="list">list</a>
	<h1>This is writing Page</h1>
	
	<form action="write.nowon" method="post">
		<p>
			<input type="text" name="writer" placeholder="name">
		</p>
		<p>
			<input type="text" name="title" placeholder="Write Title">
		</p>
		<p>
			<textarea  name="content" rows="5" cols="100" placeholder="Write content"></textarea>
		</p>
		<p>
			<button type="submit">Writing done</button>
		</p>
	
	</form>
	
</body>
</html>

 

 

BoardController

package nowon.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/board/*")
public class BoardController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Connection conn; // This is needed when connecting to DB   this is saved in the server saved box
	
    
	// Server configuration initialization
    // Inbox can be accessed by ServletConfig
	@Override
	public void init(ServletConfig config) throws ServletException {
		ServletContext sc = config.getServletContext();
//		Object obj = sc.getAttribute("myDB");
//		Connection conn = (Connection)obj;
//		
//		Connection conn = (Connection)sc.getAttribute("myDB");
//		conn=this.conn;
		
		conn = (Connection)sc.getAttribute("myDB");
		
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		System.out.println("start all address from /board/");
		System.out.println("Requested Server :"+request.getRequestURI());
	
		String uri=request.getRequestURI();
		//페이지 연결 설정
		if(uri.equals("/day0419/board/list")) {
			String sql="select * from board";
			PreparedStatement pstmt=null;
			try {
				pstmt = conn.prepareStatement(sql);
				ResultSet rs = pstmt.executeQuery();
				//collection
				//save this data so it can read this in list.jsp
				// request -> response :: request scope
				request.setAttribute("list", rs);
				
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		
			String path="/WEB-INF/board/list.jsp";
			RequestDispatcher rd = 
					request.getRequestDispatcher(path);
			rd.forward(request, response);
		} else if (uri.equals("/day0419/board/write")) {
			String path="/WEB-INF/board/write.jsp";
			RequestDispatcher rd = 
					request.getRequestDispatcher(path);
			rd.forward(request, response);
		} else if (uri.equals("/day0419/board/write.nowon")) {
			request.setCharacterEncoding("utf-8");
			String writer = request.getParameter("writer");
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			System.out.println(writer);
			System.out.println(title);
			System.out.println(content);
			// Save board table in DB
			//seq_board
			String sql = "insert into board(no, title, content, writer, created_date)"
					+ " values(seq_board.nextval,?,?,?,sysdate)";
			PreparedStatement pstmt = null;
			try {
				  pstmt = conn.prepareStatement(sql);
				  // ? 쿼리 세팅
				  pstmt.setString(1, title); // ? 1번째
				  pstmt.setString(2, content);// ? 2번째
				  pstmt.setString(3, writer);// ? 3번째
				  //쿼리 실행
				  int n = pstmt.executeUpdate();
				  System.out.println(n + "개 저장완료");
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				if(pstmt!=null) {
					try {
							pstmt.close();
					} catch (SQLException e) {
							e.printStackTrace();
					}
				}
			}

			
			
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}

 

NowonListener.java

package nowon.controller;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;


@WebListener
public class NowonListener implements ServletContextListener {

	
	
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// when server is disconnected
		Connection conn = 
		(Connection)sce.getServletContext().getAttribute("myDB");
		
		// mydb = connection conn
		
		try {
			if(conn !=null)conn.close();
			System.out.println(">>>>> DBCP disconnected!");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		Context initContext;
		try {
		initContext = new InitialContext();
		Context envContext = (Context)initContext.lookup("java:/comp/env");
		DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
		Connection conn = ds.getConnection();
		
		// 서버영역에 보관하고 공유해서 쓴다는 표현 = getServletContext
					// 메서드 안에있는 것들이 죽지않고 서버가 끝날 때까지 가게하는거
					// sc라는 변수에 ServletContext클래스 객체를 생성하고
					// setAttribute("연결에 사용할 이름", 보관해야할 객체);
					// 보관하게 된다면 다른 페이지에서도 연결해서 쓸 수 있음
		
		//saving into server space
		ServletContext sc=sce.getServletContext();// Connection Object to save
		sc.setAttribute("myDB", conn);
		
		} catch (NamingException | SQLException e) {
			e.printStackTrace();
		}
	}

  
	
}

context.xml

<!-- context.xml -->

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

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

</Context>

https://tomcat.apache.org/tomcat-10.1-doc/jndi-datasource-examples-howto.html#:~:text=1.%20Context%20configuration

 

Apache Tomcat 10 (10.1.0-M14) - JNDI Datasource How-To

JNDI Datasource configuration is covered extensively in the JNDI-Resources-HOWTO. However, feedback from tomcat-user has shown that specifics for individual configurations can be rather tricky. Here then are some example configurations that have been poste

tomcat.apache.org

아파치 톰캣에서 설정 주소 복사

 

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">

  <display-name>day0419</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <resource-ref>
 <description>Oracle Datasource example</description>
 <res-ref-name>jdbc/myoracle</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>
  
</web-app>

 

 

반응형