JSP 에서 alert 창 띄우기

박영준·2024년 6월 13일
0

JSP

목록 보기
10/17

JSP 에서 JDBC 로 Oracle DB 연동 후, 데이터 조회하기 과정을 진행한 것으로 가정하고 작성했다.

1. 기존의 코드

<%@page import="javax.sql.*"%>
<%@page import="javax.naming.*"%>
<%@page import="java.sql.*"%>
<%@ 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>
	
	<style>
		th {
			color: blue;
		}
	</style>
	
</head>
<body>
	중략...

	<%	
		Connection con = null;
		Boolean connect = false;	

		PreparedStatement pstmt = null;
		
		ResultSet rs = null;
	
		try {			
			Context init = new InitialContext();
			DataSource ds = (DataSource) init.lookup("java:comp/env/Oracle_park");
			con = ds.getConnection();
			
			connect = true;
			
			if(connect = true) { %>
			<h3>DB 연결 성공</h3>
		<%	} else { %>
			<h3>DB 연결 실패</h3>
		<%  }
	
			중략...
		%>	
				중략...
		<% 	} 
		
	    중략...
	 %>
    </table>
</body>
</html>

alert 창을 띄우기 위해서는 script 태그 내부에 alert 를 사용하면 된다.
그러나 sctipt 태그의 위치가 고민이었다.

  1. head 태그 내부(style 태그 하단)에 위치하는 경우

    • hTML을 파싱하던 도중에 JS를 실행하게 됨
    • 따라서, JS 파일이 크거나 인터넷이 느릴 경우에는 웹사이트를 띄우는데 오래 걸림
  2. body 태그 최하단에 위치하는 경우

    • 웹페이지를 전부 불러온 이후에 script를 가져옴
    • 장점: 사용자가 웹페이지를 보기까지 지연 시간이 없음
      단점: script를 마지막에 불러오기 때문에, 그 전에 웹페이지의 동적 요소들이 정상 작동하지 않을 수 있음
  3. body 태그 중간에 위치하는 경우

    • html을 읽는 과정에서 script를 만나는 지점(즉, 중단 지점)이 생겨버려서 지연될 수 있음
    • 그러나 JSP의 경우, 중간지점에 script를 사용하기도 함

2. alert 창 띄우기

body 태그 중간에 script를 위치시켜 alert창을 띄우도록 했다.
(정확히는, if문 반환값으로)

방법 1. script 태그 사용

<%@page import="javax.sql.*"%>
<%@page import="javax.naming.*"%>
<%@page import="java.sql.*"%>
<%@ 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>
	
	<style>
		th {
			color: blue;
		}
	</style>
	
</head>
<body>
	<table border="1">
		<tr>
			<th>번호</th>
			<th>이름</th>
			<th>나이</th>
			<th>성별</th>
		</tr>

	<%	
		Connection con = null;
		Boolean connect = false;	

		PreparedStatement pstmt = null;
		
		ResultSet rs = null;
	
		try {			
			Context init = new InitialContext();
			DataSource ds = (DataSource) init.lookup("java:comp/env/Oracle_park");
			con = ds.getConnection();
			
			connect = true;
			
			if(connect = true) { %>
			<script>alert("DB 연결 성공");</script>
		<%	} else { %>
			<script>alert("DB 연결 실패");</script>
		<%  }
	
			pstmt = con.prepareStatement("SELECT * FROM MEMBER");
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				Long num = rs.getLong("NUM");
				String name = rs.getString("NAME");
				String age = rs.getString("AGE");
				String sex = rs.getString("SEX");
		%>	
				<tr>
					<td><%=num%></td>
					<td><%=name%></td>
					<td><%=age%></td>
					<td><%=sex%></td>
				</tr>
		<% 	} 
		
	    } catch(Exception ex) {
			connect = false;
			ex.printStackTrace();
			
		} finally {
			if(rs != null) rs.close();
			if(pstmt != null) pstmt.close();
			if(con != null) con.close();
		}
	 %>
    </table>
</body>
</html>

방법 2. out.println() & script 태그 사용

중략...

<!DOCTYPE html>
<html>
<head>
	중략...
	
</head>
<body>
	중략...

	<%	
		중략...
	
		try {			
			Context init = new InitialContext();
			DataSource ds = (DataSource) init.lookup("java:comp/env/Oracle_park");
			con = ds.getConnection();
			
			connect = true;
			
			if(connect = true) {
				out.println("<script>alert('DB 연결 성공');</script>");
			} else {
				out.println("<script>alert('DB 연결 실패');</script>");
		  	}
          
          	중략...

3. 웹페이지 확인하기


참고: script 태그는 어느 곳에 위치하는 것이 좋을까?
참고: TIL 14 | script 태그 위치에 따른 차이점

profile
개발자로 거듭나기!

0개의 댓글