Cohe

6-1 JSP-JDBC 연동2 본문

개발 언어/JSP

6-1 JSP-JDBC 연동2

코헤0121 2024. 4. 12. 18:03
728x90
  • 오늘은 어제 배웠던 JSP-JDBC 연동에 이어 updteUser와 deleteUser을 알아보자

Mypage

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%
    String id = (String)session.getAttribute("id"); //type casting 필요
    if(id==null){

        response.sendRedirect("login.jsp");
    }
    %>


<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1><%=id %>님 환영합니다.</h1>

<a href="logout.jsp">로그아웃</a><br>
<a href="modify_ok">정보수정</a><br> 
<!-- DB로 부터 객체 정보를 담아와서 vo에 담아줘야 한다, update.jsp 를 그대로 나온다. 값을 변경해야 한다.
 update_ok로 가야함. 수정이 다되면 my_page로 다시 온다.  -->
<a href="delete_ok">회원탈퇴</a>
</body>
</html>
  • 이 코드를 보면 modify_ok로 정보를 수정한다.

modyfy_ok

  • dao에서 있는지 없는지 확인하고, 있으면 정보를 쭉 보낸다
  • 사실 이미 login이 완성 된 상태이기 때문에 회원 정보가 안보이는 경우는 거의 없다!

package com.jdbc.ok;

import java.io.IOException;  
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;

import com.jdbc.domain.UserDAO;  
import com.jdbc.domain.UserVO;

@WebServlet("/modify\_ok")  
public class modify\_ok extends HttpServlet {  
private static final long serialVersionUID = 1L;

public modify_ok() {
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //정보 수정 페이지로 이동하기 위해 db에서 정보를 가져오는 작업
    //id -> 세션을 통해 얻어옴
    HttpSession session = request.getSession();
    String id = (String)session.getAttribute("id");

    UserDAO dao = UserDAO.getInstance();

    UserVO vo = dao.getInfo(id);

    //vo를 request에 통째로 강제 저장하고 포워드 처리
    //임의로 지정해서 집어넣기 때문에 강제 저장
    request.setAttribute("vo", vo);
    request.getRequestDispatcher("update.jsp").forward(request, response);
}

}

dao 수정


//회원 정보 수집
    public UserVO getInfo(String id) {
        UserVO vo = null;
        String sql = "select * from user where id = ?";

        try {
            int result = 0;
            Class.forName("com.mysql.cj.jdbc.Driver");
             conn = DriverManager.getConnection(url, user, password);
             System.out.println(conn);
             System.out.println("데이터베이스 접속 성공.");

             pstmt = conn.prepareStatement(sql);

             pstmt.setString(1, id); // id 값이 문자열이므로 setString을 사용하여 데이터 타입을 지정

             rs = pstmt.executeQuery(); // 쿼리 실행 결과를 ResultSet에 저장

             if (rs.next()) {
                 result = 1; // 존재하는 경우 1, 존재하지 않는 경우 0

                 String name = rs.getString("name");
                 String pw = rs.getString("pw");
                 String phone1 = rs.getString("phone1");
                 String phone2 = rs.getString("phone2");
                 String gender = rs.getString("gender");

                 vo = new UserVO(id, pw, name,phone1, phone2, gender);

             }

             if(result != 0) {
                 System.out.println("SQL성공");
             }else {
                 System.out.println("SQL실패");
                 }    

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
             try {
                 if(conn!=null) conn.close();
                 if(pstmt!=null) pstmt.close();
                 if(rs!=null) rs.close();

             } catch (Exception e) {
                // TODO: handle exception
             }
        }

        return vo;
    }

update.jsp 생성

  • update jsp 파일을 생성한다.
  • 코드에 대한 주석 추가해놨다.
<%@page import="com.jdbc.domain.UserVO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

    <%
    //id는 세션을 통해서
    String id = (String)session.getAttribute("id"); //사용자 인증 정보를 지속적으로 확인한다!

    UserVO vo = (UserVO)request.getAttribute("vo");


    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>update.jsp</title>
</head>
<body>
    <h2>회원 수정 연습</h2>
    <body>
    <form action="update_ok" method="post">
    ID : <input type="text" name="id" value="<%=id%>" readonly><br> 
    PW : <input type="password" name="pw" disabled><br>
    이름 : <input type="text" name="name" value="<%=vo.getName()%>"><br>
    <select name="phone1" >
        <option <%=vo.getPhone1().equals("010") ? "selected":""%>>010</option>
        <option <%=vo.getPhone1().equals("011") ? "selected":""%>>011</option>
        <option <%=vo.getPhone1().equals("018") ? "selected":""%>>018</option>
    </select>
    -<input type="text" name = phone2 value="<%= vo.getPhone2()%>"><br>
    <%if(vo.getGender()==null || vo.getGender().equals("m")){ %>
    <input type="radio" name="gender" value="m" checked/>남자
    <input type="radio" name="gender" value="w"/>여자 <br>

    <%}else{ %>
    <input type="radio" name="gender" value="m"/>남자
    <input type="radio" name="gender" value="w" checked/>여자 <br>

    <%} %>
    <input type = "submit" value= "수정">
    </form>
    <form action="modify_ok" method="post">
          <button type="submit">비밀번호 수정</button>
    </form>



</body>
</html>

update_ok


package com.jdbc.ok;

import java.io.IOException;
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 com.jdbc.domain.UserDAO;
import com.jdbc.domain.UserVO;

@WebServlet("/update_ok")
public class update_ok extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public update_ok() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //form에서 들어오는 값 처리

        request.setCharacterEncoding("utf-8");

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String phone1 = request.getParameter("phone1");
        String phone2 = request.getParameter("phone2");
        String gender = request.getParameter("gender");

        //DAO 객체 생성 -> 싱글톤 작업을 할 것임! 딱 하나의 dao 객체를 만듦 -> db와 작업함!

        UserDAO dao = UserDAO.getInstance();

        //VO 객체 생성
        UserVO vo = new UserVO(id, null, name, phone1, phone2, gender);

        //회원가입 처리
        int result = dao.update(vo);

        if(result ==1) {//성공시 처리
            response.sendRedirect("update_success.jsp");
        }else { //실패 시 처리
            response.sendRedirect("mypage.jsp");
        }

    }

}

UserDAO 수정 - update 메소드 추가

    public int update(UserVO vo) {
        int result = 0;

        String sql = "update user set name=?, phone1=?, phone2=?, gender=? where id=?";

        try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             conn = DriverManager.getConnection(url, user,password);
             System.out.println(conn);
             System.out.println("데이터베이스 접속 성공.");
             pstmt = conn.prepareStatement(sql);

             pstmt.setString(1,vo.getName());
             pstmt.setString(2,vo.getPhone1());
             pstmt.setString(3,vo.getPhone2());
             pstmt.setString(4,vo.getGender());
             pstmt.setString(5,vo.getId());

             result = pstmt.executeUpdate();

             if(result != 0) {
                 System.out.println("SQL성공");
             }else {
                 System.out.println("SQL실패");
                 }
        }  catch (ClassNotFoundException e) {
             System.out.println("드라이버 로드 실패");
          }catch (SQLException sqle) {
             System.out.println("SQL 연동 오류");
             System.out.println(sqle.getMessage());
          }finally {
             try {

             } catch (Exception e) {
                // TODO: handle exception
             }
          }

        return result;

    }

update_success.jsp


<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<h1>회원 정보가 수정되었습니다.</h1>
<a href="mypage.jsp">my page로 이동</a>
</body>
</html>

Delete 구현

  • 정말 간단하다!!!

delete ok

package com.jdbc.ok;

import java.io.IOException;
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;

import com.jdbc.domain.UserDAO;

@WebServlet("/delete_ok")
public class delete_ok extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public delete_ok() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String id = (String)session.getAttribute("id");

        UserDAO dao = UserDAO.getInstance();
        int result = dao.delete(id);
        if(result ==1) { //success
            session.invalidate();
            response.sendRedirect("login.jsp");
        }else {//fail
            response.sendRedirect("mypage.jsp");
        }
    }

}

UserDAO delete 메소드 구현


    public int delete(String id) {
        int result =0;

        String sql = "delete from user where id=?";
        try {
             Class.forName("com.mysql.cj.jdbc.Driver");
             conn = DriverManager.getConnection(url, user,password);

             pstmt = conn.prepareStatement(sql);

             pstmt.setString(1,id);

             result = pstmt.executeUpdate();

        }  catch (ClassNotFoundException e) {
             System.out.println("드라이버 로드 실패");
          }catch (SQLException sqle) {
             System.out.println("SQL 연동 오류");
             System.out.println(sqle.getMessage());
          }finally {
             try {
                 if(conn!=null) conn.close();
                 if(pstmt!=null) pstmt.close();
                 if(rs!=null) rs.close();
             } catch (Exception e) {
                // TODO: handle exception
             }

모두 배워놨던 것이라서 자세한 설명은 생략한다.


Server

  • context.xml에서 아래와 같은 코드를 추가하면 미리 연결하게끔하여 코딩이 훨씬 수월하다.
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context privileged="true">

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <Resource
    auth="Container"
    driverClassName = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306/jdbctest?serverTimezone=Asia/Seoul"
    username = "jdbc"
    password = "jdbc"
    name = "jdbc/mysql"
    type = "javax.sql.DataSource"
    maxActive = "300"
    maxWait = "1000"
    />
    <Resource
    auth="Container"
    driverClassName = "com.mysql.cj.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306/myweb?serverTimezone=Asia/Seoul"
    username = "root"
    password = "root"
    name = "jdbc/mysql2"
    type = "javax.sql.DataSource"
    />
</Context>

'개발 언어 > JSP' 카테고리의 다른 글

JSP mini project : mypage 실습3 - 로그인  (0) 2024.04.15
JSP mini project : mypage 실습  (0) 2024.04.15
6. JSP-JDBC 연동  (0) 2024.04.11
5. javaBean  (0) 2024.04.11
4. application, param, include, forward, action tag, error page  (0) 2024.04.09