class 22-23 : JSP, DB 연동

yoneeki·2023년 3월 3일
0

training-jp

목록 보기
15/31

서블릿으로 데이터 전달

CheckBoxSender.java


import java.io.IOException;
import java.io.PrintWriter;

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("/jsp02/CheckBoxSender")
public class CheckBoxSender extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public CheckBoxSender() {
		super();

	}

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

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset='UTF-8'>");
		out.println("<title>Hello JSP</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Check Box 데이터 보내기</h1>");
		out.println("<form method='GET' action='/jsp02/CheckBoxReceiver'>");
		out.println("<p>관심 분야를 선택하세요.</p>");
		out.println("<input type='checkbox' name='interest' value='자바'><span>자바</span>");
		out.println("<input type='checkbox' name='interest' value='파이썬'><span>파이썬</span>");
		out.println("<input type='checkbox' name='interest' value='자바스크립트'><span>자바스크립트</span>");
		out.println("<input type='checkbox' name='interest' value='C'><span>C</span>");
		out.println("<input type='checkbox' name='interest' value='Go'><span>Go</span>");
		out.println("<button>send</button>");
		out.println("</form>");
		// out.println("<a href=''>뒤로가기</a><br>");
		// out.println("<a href='javascript:history.back();'>뒤로가기</a>");
		out.println("</body>");
		out.println("</html>");
	}

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

		doGet(request, response);
	}

}

CheckBoxReceiver.java


import java.io.IOException;
import java.io.PrintWriter;

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("/jsp02/CheckBoxReceiver")
public class CheckBoxReceiver extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public CheckBoxReceiver() {
		super();

	}

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

		String[] checkeds = request.getParameterValues("interest");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset='UTF-8'>");
		out.println("<title>Hello JSP</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Check Box 데이터 받기</h1>");
		out.println("<ul>");
		for (int i = 0; i < checkeds.length; i++) {
			out.println("<li>" + (i + 1) + " : " + checkeds[i] + "</li>");
		}
		out.println("</ul>");
		out.println("<a href='javascript:history.back();'>뒤로가기</a>");
		out.println("</body>");
		out.println("</html>");
	}

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

	}

}

JSP로 데이터 전달

SendRedirect

Login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>

	<h1>LOGIN</h1>
	<form method="GET" action="Login_ok.jsp">
		<div>
			<input type="text" name="userId" />
		</div>
		<div>
			<input type="password" name="userPw">
		</div>
		<div>
			<button type="submit">로그인</button>
			<button type="reset">취소</button>
		</div>
	</form>
</body>
</html>

Login_ok.jsp


<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LOGIN OK</title>
</head>
<body>

	<%
	String userId = request.getParameter("userId");
	String userPw = request.getParameter("userPw");
	String userName = "김회원";
	%>


	<%
	if (userId.equals("kim1234") && userPw.equals("1234")) {
		response.sendRedirect("Login_success.jsp?userName=" + URLEncoder.encode(userName, "UTF-8"));
	} else {
		out.println("<script> alert('아이디 및 패스워드 확인 요망'); history.back(); </script>");
	}
	%>

</body>
</html>

Login_success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LOGIN SUCCESS</title>
</head>
<body>
	<%
		String userName = request.getParameter("userName");
	%>

	<h1><%=userName%> 님, 로그인 성공!</h1>
</body>
</html>

RequestDispatcher

Login_forward.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Forward</title>
</head>
<body>

	<h1>LOGIN FORWARD</h1>
	<form method="POST" action="Login_ok_forward.jsp">
		<div>
			<input type="text" name="userId" />
		</div>
		<div>
			<input type="password" name="userPw">
		</div>
		<div>
			<button type="submit">로그인</button>
			<button type="reset">취소</button>
		</div>
	</form>
</body>
</html>

Login_ok_forward.jsp

<%@page import="java.net.URLEncoder"%>
<%@ 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>
	<%
	String userId = request.getParameter("userId");
	String userPw = request.getParameter("userPw");
	String userName = "김회원";
	
	/** setAttribute **/
	/*pageContext.setAttribute("name", "나는 page Context 입니다."); // 단일 페이지
	request.setAttribute("name", "나는 request 입니다."); // forward(O), sendRedirect(X)
	session.setAttribute("name", "나는 session 입니다."); // 세션이 사라질 때까지
	application.setAttribute("name", "나는 application 입니다."); // 서버 종료 시까지*/
	%>


	<%
	if (userId.equals("kim1234") && userPw.equals("1234")) {
		request.setAttribute("userName", userName);
		request.setAttribute("userCity", "서울");
		request.setAttribute("userAge", 30);
		RequestDispatcher dispatcher = request.getRequestDispatcher("Login_success_forward.jsp");
		dispatcher.forward(request, response);
		// SendRedirect와는 달리 Forward는 정보를 가지고 갈 수 있다
	} else {
		out.println("<script> alert('아이디 및 패스워드 확인 요망'); history.back(); </script>");
	}
	%>
</body>
</html>

Login_success_forward.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Success Forward</title>
</head>
<body>
	<%
	String userName = (String) request.getAttribute("userName");
	String userCity = (String) request.getAttribute("userCity");
	int userAge = (int) request.getAttribute("userAge");
	%>
	<h1>안녕하세요, <%=userName%> 님 !</h1>
	<p>(<%=userCity%> 거주, <%=userAge%> 세)</p>
</body>
</html>

이클립스-오라클 DB연동

ojdbc 드라이버를 다이나믹 웹 프로젝트의 webapp -> WEB-INf -> lib에 넣어둔다.
이 드라이버는 (오라클을 설치했다면) oraclexe -> app -> oracle -> product -> 11.2.0 (버전명) -> server -> jdbc -> lib 안에 존재한다 (ojdbc6.jar)

ojdbc.jsp

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	String driver = "oracle.jdbc.OracleDriver";
	String url = "jdbc:oracle:thin:@localhost:1521:xe";
	String id = "YONEE001";
	String pw = "0000";
	
	Connection conn = null; // 커넥션 객체 초기화
	
	Class.forName(driver); // 드라이버 가져오겠다
	conn = DriverManager.getConnection(url, id, pw); // 커넥션 연결
	
	System.out.println(conn); // 연결 확인
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>

</body>
</html>

간단한 회원가입, 로그인

SQL

CREATE TABLE MEMBER (
	USERID VARCHAR(20) PRIMARY KEY,
    USERPW VARCHAR(20) NOT NULL
);

ALTER TABLE MEMBER ADD USERNAME VARCHAR(10);
ALTER TABLE MEMBER ADD GENDER VARCHAR(10);
ALTER TABLE MEMBER ADD GRADE VARCHAR(10);

COMMIT;

Join.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원가입</title>
</head>
<body>

	<form method="GET" action="Join_process.jsp">
		<div>
			<label><span>아이디 :</span><input type="text" name="userID"></label>
		</div>
		<div>
			<label><span>패스워드 :</span><input type="password"
				name="userPW"></label>
		</div>
		<div>
			<label><span>이름 : </span><input type="text" name="userName"></label>
		</div>
		<div>
			<span>성별 : </span> 남자<input type="radio" name="gender" value="남자">&nbsp;&nbsp;
			여자<input type="radio" name="gender" value="여자">
		</div>
		<div>
			<span>학력 : </span> <select name="grade">
				<option value="elementary">초졸</option>
				<option value="middle">중졸</option>
				<option value="high">고졸</option>
				<option value="univ">대졸</option>
				<option value="master">대학원졸</option>
			</select>
		</div>
		<div>
			<button>회원가입</button>
			&nbsp;
			<button type="reset">취소</button>
		</div>
	</form>

	<a href="Login.jsp">로그인</a>
</body>
</html>

Join_process.jsp

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

<%
String userID = (String) request.getParameter("userID");
String userPW = (String) request.getParameter("userPW");
String userName = (String) request.getParameter("userName");
String gender = (String) request.getParameter("gender");
String grade = (String) request.getParameter("grade");
%>

<%
String driver = "oracle.jdbc.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String id = "YONEE001";
String pw = "0000";

Connection conn = null; // 커넥션 객체 초기화
PreparedStatement pstmt = null;

Class.forName(driver); // 드라이버 가져오겠다
conn = DriverManager.getConnection(url, id, pw); // 커넥션 연결

String sql = "INSERT INTO MEMBER (USERID, USERPW, USERNAME, GENDER, GRADE) VALUES (?, ?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userID);
pstmt.setString(2, userPW);
pstmt.setString(3, userName);
pstmt.setString(4, gender);
pstmt.setString(5, grade);

int result = pstmt.executeUpdate(); 
// 데이터에 변경을 주는 경우 (select 제외 전부) 
// 영향을 준 개수가 나옴 (1이 뜰 것임 성공했다면)

//ystem.out.println(result);

%>



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Join Process</title>
</head>
<body>
<%
if(result > 0) {
	out.println("<alert>회원가입 완료</alert>");
	out.println("<");
	//out.println("<h2>회원가입 완료</h2>");
} else {
	out.println("<alert>회원가입 실패</alert>");
	//out.println("<h2>회원가입 실패</h2>");
}
%>
</body>
</html>

Login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
</head>
<body>

	<form method="GET" action="Login_process.jsp">
		<div>
			<label><span>아이디</span><input type="text" name="userID"></label>
		</div>
		<div>
			<label><span>패스워드</span><input type="password" name="userPW"></label>
		</div>
		<div>
			<button>로그인</button>&nbsp;<button type="reset">취소</button>
		</div>
	</form>
	
	<a href="Join.jsp">회원가입</a>
</body>
</html>

Login_process.jsp

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

<%
String userID = (String) request.getParameter("userID");
String userPW = (String) request.getParameter("userPW");

//System.out.println(userID + ", " + userPW);
%>

<%
String driver = "oracle.jdbc.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String id = "YONEE001";
String pw = "0000";

Connection conn = null; // 커넥션 객체 초기화
PreparedStatement pstmt = null;
ResultSet rs = null;

Class.forName(driver); // 드라이버 가져오겠다
conn = DriverManager.getConnection(url, id, pw); // 커넥션 연결

//String sql = "INSERT INTO MEMBER (USERID, USERPW) VALUES (?, ?)";
String sql = "SELECT * FROM MEMBER WHERE USERID = ? AND USERPW = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userID);
pstmt.setString(2, userPW);
rs = pstmt.executeQuery(); // SELECT의 실행 결과가 담김
%>



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Process</title>
</head>
<body>
	<%
	if (rs.next()) {
		// 중복 허용을 하지 않는다는 가정 하에 1개가 나옴 (id - primary)
		// eof : END OF FILE....다음 줄을 읽어라 
		String _userID = rs.getString("USERID");
		String _userPW = rs.getString("USERPW");
		String _userName = rs.getString("USERNAME");
		String _gender = rs.getString("GENDER");
		String _grade = rs.getString("GRADE");
		//System.out.println(_userID + ", " + _userPW);
		session.setAttribute("userID", _userID);
		session.setAttribute("userName", _userName);
		session.setAttribute("gender", _gender);
		session.setAttribute("grade", _grade);
		response.sendRedirect("Login_ok.jsp");
	} else {
		//System.out.println(userID + ", " + userPW);
		out.println("<script>alert('아이디 패스워드 확인 요망'); history.back();</script>");
	}
	%>
</body>
</html>

Login_ok.jsp

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

<%
String userID = (String) session.getAttribute("userID");
String userName = (String) session.getAttribute("userName");
String gender = (String) session.getAttribute("gender");
String grade = (String) session.getAttribute("grade");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LOGIN OK</title>
</head>
<body>

	<h2><%=userName%>
		님, 안녕하세요 (<%=userID%>)
	</h2>
	<hr>
	<p><%=gender%>, <%=grade%></p>
</body>
</html>

Scope

Scope_first.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FIRST</title>
</head>
<body>
	<%
	pageContext.setAttribute("name", "나는 page Context 입니다."); // 단일 페이지
	request.setAttribute("name", "나는 request 입니다."); // forward(O), sendRedirect(X)
	session.setAttribute("name", "나는 session 입니다."); // 세션이 사라질 때까지
	application.setAttribute("name", "나는 application 입니다."); // 서버 종료 시까지
	
	out.println("<h2>==== scope first ====</h2>");
	out.println("<p>pageContext : " + pageContext.getAttribute("name") + "</p>");
	out.println("<p>request : " + request.getAttribute("name") + "</p>");
	out.println("<p>session : " + session.getAttribute("name") + "</p>");
	out.println("<p>application : " + application.getAttribute("name") + "</p>");
	
	// 이거 때문에 이 페이지는 그냥 스쳐지나가고 바로 Scope_second만 보여짐
	// EX ) jsp (유효성 검증 등 요청) -> servelt(디스패처) -> 다시 jsp (결과 반환)
	RequestDispatcher dispatcher =  request.getRequestDispatcher("Scope_second.jsp");
	dispatcher.forward(request, response);
	%>
</body>
</html>

Scope_second.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SECOND</title>
</head>
<body>
	<%
	//pageContext.setAttribute("name", "나는 page Context 입니다."); // 단일 페이지
	//request.setAttribute("name", "나는 request 입니다."); // forward(O), sendRedirect(X)
	//session.setAttribute("name", "나는 session 입니다."); // 세션이 사라질 때까지
	//application.setAttribute("name", "나는 application 입니다."); // 서버 종료 시까지
	
	out.println("<h2>==== scope second ====</h2>");
	out.println("<p>pageContext : " + pageContext.getAttribute("name") + "</p>");
	out.println("<p>request : " + request.getAttribute("name") + "</p>");
	out.println("<p>session : " + session.getAttribute("name") + "</p>");
	out.println("<p>application : " + application.getAttribute("name") + "</p>");
	
	out.println("<a href='Scope_third.jsp'>THIRD로 가기</a>");
	%>
</body>
</html>

Scope_third.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>THIRD</title>
</head>
<body>

	<%
	out.println("<h2>==== scope third ====</h2>");
	out.println("<p>pageContext : " + pageContext.getAttribute("name") + "</p>");
	out.println("<p>request : " + request.getAttribute("name") + "</p>");
	out.println("<p>session : " + session.getAttribute("name") + "</p>");
	out.println("<p>application : " + application.getAttribute("name") + "</p>");
	
	out.println("<a href='Scope_first.jsp'>FIRST로 가기</a>");
	%>
</body>
</html>
profile
Working Abroad ...

0개의 댓글