JSP

김병현·2022년 5월 9일
0

Java

목록 보기
4/4

JSP

Java Server Page. HTML내에 자바 코드를 삽입하여 웹 서버에서 동적으로 웹 페이지를 생성하여 웹 브라우저에 돌려주는 서버 사이드 스크립트 언어입니다.

<%@ 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>
	<h3>JSP Study</h3><br>
	<%@ page import = "java.util.Date"%>
	오늘의 날짜는 <%= new Date() %>
</body>
</html>

# <% %> : script retag. JSP 코드 작성 구간

MVC

Model-View_Controller. 모델-뷰-컨트롤러는 소프트웨어 공학에서 사용되는 소프트웨어 디자인 패턴입니다.

MVC1

소규모 웹페이지 개발에 적합합니다. HTML 코드와 JSP 코드를 혼용하여 개발합니다.

Database 연결

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>	# sql 라이브러리(Java Library) import

<body>
# 오라클
<%	# 변수 초기화
	Connection conn = null;   # DB를 연결하는 객체
	String driver = "oracle.jdbc.driver.OracleDriver";	# Oracle Driver에 접속
	String url = "jdbc:oracle:thin:@localhost:1521:XE";	# 포트:오라클 버전
	Boolean connect = false;  # 접속 성공 여부 확인하는 변수
		 
	try {
		Class.forName(driver);  # 오라클 드라이버 로드
		conn = DriverManager.getConnection(url,"hr","1234");  # url 주소, 계정, 비밀번호

		connect = true;
		conn.close();
		} catch (Exception e) {
		   connect = false;
		   e.printStackTrace();
		}
%>
--------------------------
# MySQL
<%	 # 변수 초기화
	Connection conn = null;   # DB를 연결하는 객체
	String driver = "com.mysql.jdbc.driver";   # MySQL Driver에 접속
	String url = "jdbc:mysql://localhost:3306/mydb";	# 포트/DB명
	Boolean connect = false;  # 접속 성공 여부 확인하는 변수
		 
	try {
		Class.forName(driver);  # MySQL 드라이버 로드
		conn = DriverManager.getConnection(url,"root","1234");  # url 주소, 계정, 비밀번호
		     
		connect = true;
		conn.close();
		} catch (Exception e) {
			connect = false;
		    e.printStackTrace();
		}
%>
--------------------------
# MS-SQL
<%	# 변수 초기화
	Connection conn = null;   # DB를 연결하는 객체
	String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";   # MSSQL Driver에 접속
	String url = "jdbc:sqlserver://localhost:1433;DatabaseName=myDB";	# 포트;DB명
	Boolean connect = false; # 접속 성공 여부 확인하는 변수
		 
	try {
		Class.forName(driver);  # MSSQL 드라이버 로드
		conn = DriverManager.getConnection(url,"sa","1234");  # url 주소, 계정, 비밀번호
		     
		connect = true;
		conn.close();
		} catch (Exception e) {
		    connect = false;
		    e.printStackTrace();
		}
%>
</body>

Data Insert

<body>
	<form method="post" action="insert01_process.jsp">
		<p>아이디 : <input type="text" name="id"></p>	# id 변수
		<p>패스워드 : <input type="password" name="password"> </p>	# password 변수 
		<p>이름 : <input type="text" name="name"></p>	# name 변수
		<p>이메일 : <input type="text" name="email">	</p> # email 변수
		<p><input type="submit" values="전송"></p>
	</form>
</body>

# method="POST" : http 헤더 앞에 값을 넣어 전송, 강력한 보안, 전송 용량의 제한이 없음 → 주로 Create, Update, Delete에 사용
# method="GET" : http 헤더 뒤에 값을 붙여서 전송, 취약한 보안, 전송 용량의 제한이 있음 → 주로 Read에 사용

# submit을 클릭하면 action 페이지를 호출하여 form 양식에 입력된 데이터를 전송 → action 페이지에서 전송받은 데이터를 DB에 저장

Insert Process

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>

<body>
<%@ include file="dbconn_oracle.jsp" %> # 해당 파일의 코드를 현재 페이지에 포함시킴
<%
	request.setCharacterEncoding("UTF-8");	# form에서 수신한 데이터 한글 처리
	
	String id = request.getParameter("id");	# from에서 수신한 데이터(파라미터) get
	String passwd = request.getParameter("passwd");
	String name = request.getParameter("name");
	String email = request.getParameter("email");
	
	Statement stmt = null;	# Statement 객체 : SQL 쿼리 구문을 담아서 실행하는 객체
	
	try {
		String sql = "INSERT INTO mbTbl(idx, id, pass, name, email) VALUES(seq_mbTbl_idx.nextval, '" + id + "', '" + passwd + "', '" + name + "', '" + email + "')";
        # 변수 타입에 따라 ''를 붙여줄 것 (ex. id 변수는 String이기 때문에 'id', 변수 타입이 int와 같은 경우에는 ''없이 id)
		
		stmt = conn.createStatement();
        # connection 객체를 통해서 statement 객체 생성
		# connection 객체는 include 파일에 있음
        
		stmt.executeUpdate(sql);	# statement 객체를 통해서 sql 변수을 실행		
		# stmt.executeUpdate(sql) : sql(INSERT, UPDATE, DELETE)문이 옴
		# stmt.executeQuery(sql) : sql(SELECT)문이 오면서 결과를 RESULTSET 객체로 반환 
        
        # executeUpdate의 기능
        	1. sql문을 실행
            2. select, update, delete가 정상적으로 실행된 건수를 반환
             -> 추가적인 Insert를 실행할 경우 성공 여부 확인하는 조건문에서 유용하게 사용됨
            
	} catch (Exception e) {
		out.println("mbTbl 테이블 삽입을 실패하였습니다.");	// jsp에선 System.out.println에서 System이 제외
		out.println(e.getMessage());
	} finally {
		if (stmt != null) {
			stmt.close();
		}
		if (conn != null) {
			conn.close();
		}
	}
%>

Select

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>

<body>
<%@ include file="dbconn_oracle.jsp"%>
<table width="500" border="1">	# 표 생성
	<tr>	# 표 컬럼 생성
		<th>아이디</th>
		<th>비밀번호</th>
		<th>이름</th>
		<th>email</th>
		<th>city</th>
		<th>phone</th>
	<tr/>

	<%
		ResultSet rs = null;	# ResultSet 객체는 DB의 테이블을 Select에서 나온 결과(레코드셋)를 담은 객체
		Statement stmt = null;	# SQL 쿼리를 담아서 실행하는 객체
		
		try {
			String sql = "SELECT * FROM mbTbl";	# String이기 때문에 쿼리 문법처럼 ; 작성하지 않아도 됨
			stmt = conn.createStatement();	# connection 객체의 createStatement()로 stmt를 활성화
			
			rs = stmt.executeQuery(sql);	# select한 결과를 ResultSet객체에 저장 필수
			
			while (rs.next()) {	# DB row 수만큼 반복하여 변수값으로 할당하여 HTML을 통하여 출력
				String id = rs.getString("id");	
				String pw = rs.getString("pass");	# select 결과이기 때문에 DB 컬럼명과 동일하게 작성. form의 name 속성값이 아님. 데이터를 받아오는 곳이 어딘지 고려하여 작성할 것
				String name = rs.getString("name");
				String email = rs.getString("email");
				String city = rs.getString("city");
				String phone = rs.getString("phone");
			%>	
				<tr>	# 테이블 row
					<td><%= id %></td>
					<td><%= pw %></td>
					<td><%= name %></td>
					<td><%= email %></td>
					<td><%= city %></td>
					<td><%= phone %></td>
				<tr/>
		<% 		
			}
		} catch(Exception e) {
			out.println("테이블 호출을 실패");
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
	%>
</table>
</body>

Update

# HTML

<body>
	<form method="post" action="insert01_process.jsp">
		<p>아이디 : <input type="text" name="id"></p>	# id 변수
		<p>패스워드 : <input type="password" name="password"> </p>	# password 변수 
		<p>이름 : <input type="text" name="name"></p>	# name 변수
		<p>이메일 : <input type="text" name="email">	</p> # email 변수
		<p><input type="submit" values="전송"></p>
	</form>
</body>
--------------------------
# JSP

<%@page import="com.mysql.cj.protocol.Resultset"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>

<body>
<%@ include file = "dbconn_oracle.jsp" %>

<%
	request.setCharacterEncoding("UTF-8");	# 데이터의 한글 처리
	
	# request 객체의 getParameter로 form에서 전송받은 값을 변수값으로 할당
	String id = request.getParameter("id");
	String passwd = request.getParameter("passwd");
	String name = request.getParameter("name");
	String email = request.getParameter("email");
	
	Statement stmt = null;
	ResultSet rs = null;	# select한 결과를 담은 객체, Select한 레코드셋을 담고 있음
	String sql = null;
	
	# form에서 전송받은 ID와 Password를 DB에서 가져온 ID, Password를 비교해서 같으면 Update 실행, 다르면 Update 실행불가
	try {
		# form에서 전송받은 ID를 조건으로 DB의 값을 select
		sql = "SELECT ID, PASS FROM mbTbl WHERE id = '" + id + "'";
		stmt = conn.createStatement();	// conn의 createStatement()를 사용해서 stmt 객체를 활성화
		
		rs = stmt.executeQuery(sql);
		
		if (rs.next()) {	# DB에 form에서 전송받은 ID가 존재하면 -> form에서 넘긴 패스워드와 DB의 Password가 일치하는지 확인
			# out.println(id + " : 해당 아이디가 존재합니다.");
		
			# DB에서 가져온 ID와 Password를 변수에 할당
			String rID = rs.getString("id");
			String rPassword = rs.getString("pass");
			
			# form에서 넘겨준 값과 DB에서 가져온 값이 일치하는지 확인
			if (id.equals(rID) && passwd.equals(rPassword)) {	// 패스워드가 일치할 떄
				# DB에서 가져온 Password와 form에서 전송받은 패스워드가 일치할 때 Update 실행
				# sql 변수 재사용하여 Update
				sql = "UPDATE mbTbl SET NAME = '" + name + "', EMAIL = '" + email + "' WHERE ID = '" + id + "'";
				
				out.println("정보가 수정되었습니다.");
				
				stmt = conn.createStatement();
				stmt.executeUpdate(sql);
			} else {	# 패스워드가 일치하지 않을 때
				out.println("패스워드가 일치하지 않습니다.");
			}
		} else {	# DB에 form에서 전송받은 ID가 존재하지 않으면
			out.println(id + " : 해당 ID가 데이터베이스에 존재하지 않습니다.");
		}
	} catch (Exception e) {
		out.println(e.getMessage());
		out.println(sql);
	} finally {
		if (rs != null) {
			rs.close();
		}
		if (stmt != null) {
			stmt.close();
		}
		if (conn != null) {
			conn.close();
		}
	}
%>
</body>

Delete

# HTML

<body>
	<form method="post" action="delete01_process.jsp">
		<p> 아이디 : <input type="text" name="id"> </p>	
		<p> 패스워드 : <input type="password" name="passwd"> </p>	
		<p> 이름 : <input type="text" name="name"> </p>	
		<p> 이메일 : <input type="text" name="email">	</p> 
		<p> <input type="submit" value="전송"> </p>
	</form>
</body>
--------------------------
# JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>   
   
<body>
<%@ include file = "dbconn_oracle.jsp" %>

<%
	request.setCharacterEncoding("UTF-8");

	String id = request.getParameter("id");
	String passwd = request.getParameter("passwd");
	String name = request.getParameter("name");
	String email = request.getParameter("email");
	
	Statement stmt = null;
	ResultSet rs = null;
	String sql = null;
	
	try {
		# form에서 전송받은 ID, Password와 DB의 ID, Password가 일치할 때 레코드 삭제(제거조건 : id 컬럼(Primary key))
		sql = "select id, pass from mbTbl where id = '" + id + "'";
		stmt = conn.createStatement();
		
		rs = stmt.executeQuery(sql);
		
		if (rs.next()) {	# ID가 존재할 때
			String rID = rs.getString("id");
			String rPassword = rs.getString("pass");
			
			# 패스워드가 일치하는지 확인. 첫번째 sql 변수값의 쿼리문에서 id를 조건으로 데이터를 조회하였기 때문에 ID는 이미 확인된 상황. 비밀번호만 일치하는지 확인하여도 무방함
			if (id.equals(rID) && passwd.equals(rPassword)) {	# 비밀번호까지 일치할 때
				sql = "delete mbTbl where id = '" + id + "'";
				out.println("해당 계정이 삭제되었습니다.");
				
				stmt = conn.createStatement();
				stmt.executeUpdate(sql);
			} else {	# 비밀번호가 일치하지 않을 때
				out.println("비밀번호가 일치하지 않습니다.");
			}
		} else {	# ID가 존재하지 않을 떄
			out.println("해당 계정은 존재하지 않습니다.");
		}
	} catch (Exception e) {
		out.println(e.getMessage());
	} finally {
		if (conn != null) {
			conn.close();
		}
		if (stmt != null) {
			stmt.close();
		}
		if (rs != null) {
			rs.close();
		}
	}
%>
</body>

statement vs preparestatement

  • statement
    한번만 실행할 경우 적합
    쿼리에 인자를 부여할 수 없음. 때문에 변수를 쿼리에 적용할 시 ''를 주의하여 작성하여야함
    매번 컴파일을 실행. cache(메모리)를 사용하지 않음
    실행할 때 쿼리문 삽입
  • preparestatement
    여러번 실행할 경우 적합
    쿼리에 인자를 부여할 수 있음. ? 인자 처리가능
    처음 컴파일을 실행 후 다시 실행할 경우 컴파일을 수행하지 않고 cache를 사용
    객체를 생성할 때 쿼리를 삽입
# preparestatement 사용

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>   
   
<body>
<%@ include file = "dbconn_oracle.jsp" %>

<%
	request.setCharacterEncoding("UTF-8");

	String id = request.getParameter("id");
	String passwd = request.getParameter("passwd");
	String name = request.getParameter("name");
	String email = request.getParameter("email");
	
	PreparedStatement pstmt = null;	# statement 대신 preparestatement 사용
	ResultSet rs = null;
	String sql = null;
	
	try {
		sql = "select id, pass from mbTbl where id = ?";	# 변수명 대신 ? 인자로 처리
		pstmt = conn.prepareStatement(sql);	# 객체 생성시 쿼리문을 넣음
		pstmt.setString(1, id);	 # (? 순서, 컬럼명). ? 인자를 사용한 경우 ? 인자가 어떤 컬럼인지 명시해줘야함
		rs = pstmt.executeQuery()	# 실행할 때는 쿼리문을 넣지 않음
		# 주의! 객체생성문과 실행문의 순서 : 객체 생성 → 실행 → 컬럼 명시 순서로 작성하여야함
        
		if (rs.next()) {
			String rID = rs.getString("id");
			String rPassword = rs.getString("pass");
            
			if (id.equals(rID) && passwd.equals(rPassword)) {
				sql = "delete mbTbl where id = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, id);
				pstmt.executeUpdate();
				
				out.println("해당 계정이 삭제되었습니다.");
			} else {
				out.println("비밀번호가 일치하지 않습니다.");
			}
		} else {
			out.println("해당 계정은 존재하지 않습니다.");
		}
	} catch (Exception e) {
		out.println(e.getMessage());
	} finally {
		if (conn != null) {
			conn.close();
		}
		if (pstmt != null) {
			pstmt.close();
		}
		if (rs != null) {
			rs.close();
		}
	}
%>
</body> 
profile
Without haste, but without rest.

0개의 댓글