[Servlet&JSP] Chap 3. Servlet을 이용한 DB와의 연동 (회원 정보 가져오기)

김승현·2021년 11월 27일
0
post-custom-banner
  • Servlet을 이용하여 userId를 검색하여 DB에서 해당 회원 정보 출력하는 로직

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>기본페이지</h1>
	<a href="/views/member/selectOneMember.html">1. ID로 회원 조회</a><br>
</body>
</html>


selectOneMember.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>회원 ID로 정보 검색</h3>
	<form action="/memberOneSelect.do" method="post">
	<input type="text" name="userId"><input type="submit" value="검색">
	</form>
	
</body>
</html>


MemberOneSelectServlet.java -> Serlvet 파일

package kr.or.test.member.controller;

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;

import kr.or.test.member.model.service.MemberService;
import kr.or.test.member.model.vo.Member;

/**
 * Servlet implementation class MemberOneSelectServlet
 */
@WebServlet("/memberOneSelect.do")
public class MemberOneSelectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MemberOneSelectServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String userId = request.getParameter("userId");

		// 검수
		// System.out.println("Veiw에서 보내온 데이터 확인 : "+userId);

		// DB에서 데이터를 가져오기 위한 비즈니스 로직 처리
		Member m = new MemberService().selectOne(userId);

		// 인코딩 설정
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");

		// 출력을 위한 out 객체 생성
		PrintWriter out = response.getWriter();

		out.println("<HTML><HEAD><TITLE>조회결과</TITLE></HEAD>");
		out.println("<BODY>");

		out.println("<div style='border:1px solid red; width:300px;'>");
		if (m != null) { // 검색한 데이터가 있다면

			out.println("<H3>[" + userId + "] 회원의 정보</H3>");
			out.println("ID : " + m.getUserId() + "<br>");
			out.println("PW : " + m.getUserPwd() + "<br>");
			out.println("이름 : " + m.getUserName() + "<br>");
			out.println("나이 : " + m.getAge() + "<br>");
			out.println("이메일 : " + m.getEmail() + "<br>");
			out.println("주소 : " + m.getAddress() + "<br>");
			out.println("폰번호 : " + m.getPhone() + "<br>");
			out.println("성별 : " + m.getGender() + "<br>");
			out.println("취미 : " + m.getHobby() + "<br>");
			out.println("가입일 : " + m.getEnrollDate() + "<br>");
			out.println("탈퇴여부 : " + m.getEndYN() + "<br>");

		} else { // 검색한 데이터가 없다면
			out.println("<H3>[" + userId + "]를 가진 회원을 검색하지 못하였습니다.</H3>");

		}
		out.println("</div>");
		out.println("<a href='/index.html'>메인 페이지로 이동 </a>");
		out.println("</BODY></HTML>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


MemberService.java

package kr.or.test.member.model.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import kr.or.test.member.model.dao.MemberDAO;
import kr.or.test.member.model.vo.Member;

public class MemberService {

	// 회원 1명에 대한 정보를 조회하는 메소드
	public Member selectOne(String userId) {

		Connection conn = null;
		Member m = null;

		// 서비스에서 DBMS 연결하고, Connection 정보만 DAO로 넘겨주도록 하기

		try {
			// 드라이버 등록
			Class.forName("oracle.jdbc.driver.OracleDriver");

			// Connection
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "servlet", "servlet");

			// check: 연결이 성공하면 oracle.jdbc.driver.OOO, 실패하면 null값
			// System.out.println("연결정보 : " + conn);

			m = new MemberDAO().selectOne(userId, conn);

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return m;
	}

}


MemberService.java

package kr.or.test.member.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import kr.or.test.member.model.vo.Member;

public class MemberDAO {

	public Member selectOne(String userId, Connection conn) {
		// JDBC에서 데이터 처리를 위한 객체

		PreparedStatement pstmt = null;
		ResultSet rset = null;
		Member m = null;

		String sql = "SELECT * FROM MEMBER WHERE userId=?";

		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, userId);

			rset = pstmt.executeQuery();

			if (rset.next()) {
				m = new Member();
				m.setUserId(rset.getString("userId"));
				m.setUserPwd(rset.getString("userPwd"));
				m.setUserName(rset.getString("userName"));
				m.setAge(rset.getInt("age"));
				m.setEmail(rset.getString("email"));
				m.setPhone(rset.getString("phone"));
				m.setHobby(rset.getString("hobby"));
				m.setAddress(rset.getString("address"));
				m.setGender(rset.getString("gender").charAt(0));
				m.setEnrollDate(rset.getDate("enrollDate"));
				m.setEndYN(rset.getString("end_YN").charAt(0));
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				rset.close();
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return m;
	}
}
profile
개발자로 매일 한 걸음
post-custom-banner

0개의 댓글