티스토리 뷰
JDBC (Java DataBase Connectivity )
- 다양한 데이터 베이스에 대해서 별도의 프로그램을 만들 필요 없이 해당 데이터 베이스의 jdbc를 이용하면 하나의 프로그램으로
데이터베이스를 관리할 수 있다.
데이터 베이스 연결순서
▶ 연결
- JDBC 드라이버 로드 - DriverManager
- 데이터베이스 연결 - Connection (커넥션 객체생성)
▶ SQL문 실행
- Statement, PreparedStatement (PrepareStatement가 더 유용)
- exexuteQuery() : sql문 실행 후 여려개의 결과값이 생기는 경우 ex ) select
- executeUpdate(): sql문 실행 후 테이블의 내용만 변경되는 경우 ex) insert, delete, update
▶ 결과전송
- ResultSet : 쿼리실행 결과 값을 받는다
▶ close처리
간단예제(회원가입, 로그인, 정보수정, 로그아웃)
- DB : Oracle SQL developer 사용
<join.html>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <form method="post" action="joinOk">
- 이름 : <input type="text" name="name" size ="5"><br>
- 아이디 : <input type="text" name="id" size ="5"><br>
- 패스워드 : <input type="password" name="pw" size ="5"><br>
- 전화번호 : <select name="phone1">
- <option value="010">010</option>
- <option value="011">011</option>
- <option value="012">012</option>
- <option value="031">031</option>
- <option value="02">02</option>
- </select>-
- <input type="text" name="phone2" size="5"> - <input type="text" name="phone3" size="5"><br>
- <input type="radio" name="gender" value="men">남
- <input type="radio" name="gender" value="women">여
- <br>
- <input type="submit" value="회원가입">
- <input type="reset" value="취소">
- </form>
- </body>
- </html>
<JoinOk.java>
- package com.javalex.ex;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.Statement;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * Servlet implementation class JoinOk
- */
- @WebServlet("/joinOk")
- public class JoinOk extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private Connection connection;
- private Statement stmt;
- private String name, id, pw, phone1, phone2, phone3, gender;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public JoinOk() {
- super();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- actionDo(request, response);
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- actionDo(request, response);
- }
- private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- name = request.getParameter("name");
- id = request.getParameter("id");
- pw = request.getParameter("pw");
- phone1 = request.getParameter("phone1");
- phone2 = request.getParameter("phone2");
- phone3 = request.getParameter("phone3");
- gender = request.getParameter("gender");
- String query = "insert into member values('" + name + "', '" + id + "', '" + pw + "', '" + phone1 + "', '" + phone2 + "', '"+ phone3 + "', '" + gender + "')";
- try {
- stmt = connection.createStatement();
- int i = stmt.executeUpdate(query);
- if(i == 1){
- response.sendRedirect("joinResult.jsp");
- } else {
- response.sendRedirect("join.html");
- }
- e.printStackTrace();
- } finally {
- try {
- if(stmt != null) stmt.close();
- if(connection != null) connection.close();
- }
- }
- }
<joinResult.jsp>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <p>회원가입이 완료되었습니다</p>
- <a href="login.html">로그인하러가기</a>
- </body>
- </html>
- DB에도 입력됨
- 로그인하러가기 클릭
<login.html>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <form method="post" action="LoginOk">
- 아이디 : <input type ="text" name="id" size= "5"><br>
- 비밀번호 : <input type ="password" name="pw" size= "5"><br>
- <input type="submit" value="로그인">
- </form>
- </body>
- </html>
로그인 클릭 -> LoginOk실행
<LoginOk.java>
- package com.javalex.ex;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- /**
- * Servlet implementation class LoginOk
- */
- @WebServlet("/LoginOk")
- public class LoginOk extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private Connection conn;
- private Statement stmt;
- private ResultSet rs;
- private String name,id,pw,phone1,phone2,phone3,gender;
- public LoginOk() {
- super();
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- response.getWriter().append("Served at: ").append(request.getContextPath());
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- actionDo(request, response);
- }
- private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- id = request.getParameter("id");
- pw = request.getParameter("pw");
- try {
- stmt = conn.createStatement();
- rs = stmt.executeQuery(query);
- while(rs.next()) { //데이터가 있다면
- name = rs.getString("name"); //select에서 가져온걸 name에 저장
- id = rs.getString("id");
- pw = rs.getString("pw");
- phone1 = rs.getString("phone1");
- phone2 = rs.getString("phone2");
- phone3 = rs.getString("phone3");
- gender = rs.getString("gender");
- HttpSession httpSession = request.getSession();
- httpSession.setAttribute("name", name);
- httpSession.setAttribute("id", id);
- httpSession.setAttribute("pw", pw);
- response.sendRedirect("loginResult.jsp"); //위에 set세션들을 loginResult.jsp로 보냄
- }
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- if(rs != null) rs.close();
- if(stmt != null) stmt.close();
- if(conn != null) conn.close();
- // TODO Auto-generated catch block
- e2.printStackTrace();
- }
- }
- }
- }
<loginResult.jsp>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%!
- String id, pw, name;
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <%
- %>
- <%=name %> 님 안녕하세요
- <!--
- <%=session.getAttribute("name") %> 님 환영합니다
- 나는 요렇게 했는데 강좌에서는 위에방법으로 함
- -->
- <a href ="modify.jsp">회원정보수정</a>
- </body>
- </html>
회원정보수정 클릭 -> modify.jsp이동
<modify.jsp>
- <%@page import="java.sql.DriverManager"%>
- <%@page import="java.sql.ResultSet"%>
- <%@page import="java.sql.Statement"%>
- <%@page import="java.sql.Connection"%>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%!
- Connection conn;
- Statement stmt;
- ResultSet rs;
- String name, id, pw, phone1, phone2, phone3, gender;
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>회원정보수정</title>
- </head>
- <body>
- <h2>정보수정페이지</h2>
- <%
- stmt = conn.createStatement();
- rs = stmt.executeQuery(query);
- while(rs.next()){
- name = rs.getString("name");
- id = rs.getString("id");
- pw = rs.getString("pw");
- phone1 = rs.getString("phone1");
- phone2 = rs.getString("phone2");
- phone3 = rs.getString("phone3");
- gender = rs.getString("gender");
- }
- %>
- <form action="ModifyOk" method="post">
- 이름 : <input type="text" name="name" value=<%=name %>><br>
- 아이디 : <input type="text" name="id" value=<%=id %>><br>
- 패스워드 : <input type="password" name="pw" size ="10"><br>
- 전화번호 : <select name="phone1">
- <option value="010">010</option>
- <option value="011">011</option>
- <option value="012">012</option>
- <option value="031">031</option>
- <option value="02">02</option>
- </select>-
- <input type="text" name="phone2" size="5" value=<%=phone2 %>> - <input type="text" name="phone3" size="5" value=<%=phone3 %>><br>
- <%
- if(gender.equals("women")){
- %>
- <input type="radio" name="gender" value="women" checked="checked">여 <input type="radio" name="gender" value="men">남
- <%
- } else {
- %>
- <input type="radio" name="gender" value="women">여 <input type="radio" name="gender" value="men" checked="checked">남
- <%
- }
- %>
- <br>
- <input type="submit" value="정보수정">
- <input type="reset" value="취소">
- </form>
- </body>
- </html>
회원번호 바꿔서 정보수정 클릭 -> ModifyOk실행
< ModifyOk.java>
- package com.javalex.ex;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Statement;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- /**
- * Servlet implementation class ModifyOk
- */
- @WebServlet("/ModifyOk")
- public class ModifyOk extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private Connection conn;
- private Statement stmt;
- String name, id, pw, phone1, phone2, phone3, gender;
- HttpSession session;
- public ModifyOk() {
- super();
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.getWriter().append("Served at: ").append(request.getContextPath());
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- actionDo(request, response);
- }
- private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- session = request.getSession();
- name = request.getParameter("name");
- id = request.getParameter("id");
- pw = request.getParameter("pw");
- phone1 = request.getParameter("phone1");
- phone2 = request.getParameter("phone2");
- phone3 = request.getParameter("phone3");
- gender = request.getParameter("gender");
- String query = "UPDATE MEMBER SET NAME = '" + name + "', ID = '" + id + "', PW = '" + pw + "', PHONE1 = '" + phone1 + "', PHONE2 = '" + phone2 + "',"
- + "PHONE3 = '" + phone3 + "', GENDER = '" + gender + "'";
- try {
- stmt = conn.createStatement();
- int i = stmt.executeUpdate(query);
- if(i == 1) {
- session.setAttribute("name", name);
- response.sendRedirect("modifyResult.jsp");
- }else {
- response.sendRedirect("modify.jsp");
- }
- e.printStackTrace();
- } finally {
- try {
- if(stmt != null)stmt.close();
- if(conn != null) conn.close();
- e.printStackTrace();
- }
- }
- }
- }
<modifyResult.jsp>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <%=session.getAttribute("name") %> 님 정보수정이 완료되었습니다.
- <a href ="modify.jsp">회원정보수정</a>
- <a href ="logout.jsp">로그아웃</a>
- </body>
- </html>
- DB도 수정됨
- 로그아웃 클릭
<logout.jsp>
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <%
- session.invalidate();
- response.sendRedirect("login.html");
- %>
- </body>
- </html>
로그아웃되며 로그인화면으로 돌아감
전~에 했던거 복습겸 해봤는데 복잡복잡하다. 요즘에는 이렇게 안하겠지??
아 자꾸 오류나서 왜이러지 했는데 lip 폴더에 파일들 inport 해줘야 한다 ㅎ
학원에서는 그냥 계속 프로젝트 복사해서 써서 깜빡하고 있었음
그냥 파일들도 싹다 import해버림
'JSP' 카테고리의 다른 글
[JSP] MVC패턴 회원 등록, 조회하는 개간단한 예제 (0) | 2021.05.02 |
---|---|
[JSP] Scope 간단예제 - 상품선택, 내가선택한 품목보기 (0) | 2018.07.13 |
[JSP] 자바빈 JavaBean (0) | 2018.07.13 |
[JSP] 쿠키(Cooki), 세션(Session) (0) | 2018.07.11 |
[JSP] Request, Response 간단한 메뉴계산 예제 (0) | 2018.07.10 |
댓글
최근에 올라온 글
최근에 달린 댓글
링크
- Total
- Today
- Yesterday