모도리는 공부중

21.01.18. JSP & Servlet - 회원정보수정, 메세지시스템 본문

K-디지털 빅데이터 분석서비스 개발자과정 20.11.02~21.04.12/JAVA

21.01.18. JSP & Servlet - 회원정보수정, 메세지시스템

공부하는 모도리 2021. 1. 18. 14:17
728x90
반응형

이메일은 클라이언트가 직접 입력한게 아니므로 세션에서 info를 가져온다.

 

저번시간에 update 숙제를 내드렸습니다. 풀이시간을 가져볼까요?

public int update(MemberDTO dto) {
# 우리는 int값으로 되돌려줄 것이므로 리턴유형은 int.
# 매개변수는 MemberDTO dto
	int cnt = 0; # 되돌려줄 리턴 초기값 설정
    
    return cnt; # 리턴타입 명시까지.
}

자, 먼저 메소드 기본 유형부터 만들고 난 다음에 가장 먼저 해야할 것은?

getConnection();

연결 메소드를 불러와서 db 연결부터 해줘야겠죠?

그리고 이건 업데이트입니다. 오랜만이라서 기억 안나겠지만 잘 다시 떠돌려볼까요?

String sql = "update web_member set pw=?, tel=?, address=? where email=?";

업데이트는 이 3가지만 기억하면 됩니다. update, set, where. 이것만 알면 언제든지 작성할 수 있어요!

psmt로 이어가줘야겠죠? 번호는 ? 첫번째부터 순서대로입니다.

추가로, psmt는 int타입으로 값을 돌려주는 것을 이용해 cnt로 값을 받아서 리턴해줄 수 있게 합니다.

이 과정에서 필요한 try, catch와 끝날 때 finally{ close(); }도 잊지 마시죠.

 

그럼 전체 코드를 확인해볼까요?

public int update(MemberDTO dto) {
	int cnt = 0;
	
	getConnection();
	
	String sql = "update web_member set pw=?, tel=?, address=? where email=?";
	
	try {
		psmt = conn.prepareStatement(sql);
		
		psmt.setString(1, dto.getPw());
		psmt.setString(2, dto.getTel());
		psmt.setString(3, dto.getAddress());
		psmt.setString(4, dto.getEmail());
		
		cnt = psmt.executeUpdate();
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		close();
	}
	
	return cnt;
}

회원정보 수정이 완료됐다면 메인화면으로 돌아오고 실패하면 update화면에 머물러있도록 updateservice코드도 수정.

if (cnt > 0) {
		System.out.println("회원정보수정 성공");
		response.sendRedirect("main.jsp"); // 성공하면 메인화면으로
	} else {
		System.out.println("회원정보수정 실패");
		response.sendRedirect("update.jps"); // 실패하면 update에서 머물러 있게.
	}

회원정보를 수정해보면 정상적으로 메인에 돌아오고 콘솔에도 회원정보수정 성공이 뜨는 것을 확인할 수 있다.

그럼 아래 배너부분도 잘 바뀌었는지 확인해볼까?

Nope. 돌아가. 네게 바꿔줄 회원정보는 없어.

어째서인지 회원정보수정 성공이라는 멘트와 다르게 전혀 바뀌지 않은 모습. 왜 그럴까?

우리는 sql문을 통해 db에 수정된 내용을 반영은 해주었지만 해당 내용을 웹 세션에까지 넣어주지는 않았기 때문에 발생하는 문제이다. 이 부분을 해결하고자 한다면 세션도 업데이트가 필요하다.

# 회원정보수정 성공 출력문 아래에 작성
session.setAttribute("info", dto); // info라는 이름으로 세션에 dto 삽입. 세션을 갱신한다.

이렇게 하면 session에 있는 info에 정보를 갱신해줄 수 있다. 갱신에 필요한 정보는 dto에 남겨져있으므로 "info",dto를 통해 가능하다. 그리고 다시 확인해보면,

배너에도 문제없이 갱신된 내용이 출력되는 것을 확인할 수 있다.

 

create table web_message(
	num number,
	send_name varchar2(200),
	receive_email varchar2(200),
	content varchar2(1000),
	day date
)

num number에 숫자를 우리가 직접 채워줄 수도 있지만 이걸 대신해주는 코드가 있다. 바로 시퀀스.

create sequence msg_num start with 1 increment by 1

사용하기 위해서 먼저 시퀀스를 생성해준다. 그 후 삽입할 위치에 insert코드를 작성.

insert into web_message values(msg_num.nextval, '아이유', 'mo@dory.com', '이번주 금요일 시간 어때요?', sysdate)

확인하는 코드 실행.

select* from WEB_MESSAGE

잘 삽입된 것을 확인할 수 있다. 시험삼아서 2개 정도 더 작성해보도록 하자.

insert into web_message values(msg_num.nextval, '나트리스', 'mo@dory.com', '메인 컨텐츠는 언제까지 숨겨둘겁니까?', sysdate)
insert into web_message values(msg_num.nextval, '돈스타브멤버', 'mo@dory.com', '봄을 꼭 보고 싶습니다. 스듀도 해야하잖아요?', sysdate)

 

문제없이 된것을 확인했다면 main.jsp로 돌아오세요. 위치는 다음과 같습니다.

message를 입력했을 때 전송받을 action과 데이터전송방식을 작성 후 각 input에 name을 달아주도록 한다.

<!-- Contact -->
	<section id="contact">
		<div class="inner">
				<section>
			<form action="InsertMessageService" method="post">
			<div class="field half first">
				<label for="name">Name</label>
				<input name="send_name" type="text"  id="name" placeholder="보내는 사람 이름" />
			</div>
			<div class="field half">
				<label for="email">Email</label>
				<input name="receive_email" type="text"  id="email" placeholder="보낼 사람 이메일"/>
			</div>

			<div class="field">
				<label for="message">Message</label>
				<textarea name="content" id="message" rows="6"></textarea>
			</div>
			<ul class="actions">
				<li><input type="submit" value="Send Message" class="special" /></li>
				<li><input type="reset" value="Clear" /></li>
			</ul>
		</form>
	</section>

InsertMessageService.java는 src - com - controller에 서블릿 생성.

package com.controller;

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;

@WebServlet("/InsertMessageService")
public class InsertMessageService extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// send_name, receive_email, content 값을 받아와서 콘솔창에 출력해주세요.
		request.setCharacterEncoding("EUC-KR");
		String send_name = request.getParameter("send_name");
		String receive_email = request.getParameter("receive_email");
		String content = request.getParameter("content");
		
		System.out.println(send_name+"/"+receive_email+"/"+content);
	}

}

결과 :

 

콘솔창에 잘 출력되는 것을 확인했으니 이제 웹에서도 표현되도록 만들어볼까요? 콘솔창에 출력하는 출력문 코드는 삭제하고 다음과 같이 만듭니다.

MessageDAO dao = new MessageDAO();
dao.insertMessage();

insertMessage에 필요한 dao와 dto도 생성이 필요하겠죠? src - com - model에 각각 class 생성.

package com.model;

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

public class MessageDAO {

	// 커넥션과 클로즈는 어떤 dao를 가도 코드가 동일하므로 MemberDAO에 있는 전역변수 선언부터 클로즈까지 복붙.
	
	private Connection conn;
	private PreparedStatement psmt;
	private ResultSet rs;

	private void getConnection() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			String url = "jdbc:oracle:thin:@localhost:1521:xe"; // 내 DB주소
			String dbid = "hr";
			String dbpw = "hr";
			
			conn = DriverManager.getConnection(url, dbid, dbpw);
			
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void close() {
		try {
			if (rs != null)
				rs.close();
			if (psmt != null) {
				psmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
package com.model;

public class MessageDTO {

//	나중에 필요해서 하나하나 수정해야하는 경우 불편할 수 있으므로 컬럼별로 모두 선언해주는 것이 꿀팁
	private int num;
	private String send_name;
	private String receive_email;
	private String content;
//	private date day; 로 선언해도 되지만 수업을 따라가기 위해 String으로 선언해준다
	private String day;
}

 

자, 이제 메세지를 입력하면 db에 저장되도록 코드를 만들어봅시다.

 

using field와 getter and setter를 MessageDAO에 자동완성으로 만든다.

//	생성자 전체 생성
	public MessageDTO(int num, String send_name, String receive_email, String content, String day) {
		this.num = num;
		this.send_name = send_name;
		this.receive_email = receive_email;
		this.content = content;
		this.day = day;
	}
//	오버로딩(중복정의)
	public MessageDTO(String send_name, String receive_email, String content) {
		this.send_name = send_name;
		this.receive_email = receive_email;
		this.content = content;
	}
	
//	게터세터
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getSend_name() {
		return send_name;
	}
	public void setSend_name(String send_name) {
		this.send_name = send_name;
	}
	public String getReceive_email() {
		return receive_email;
	}
	public void setReceive_email(String receive_email) {
		this.receive_email = receive_email;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getDay() {
		return day;
	}
	public void setDay(String day) {
		this.day = day;
	}
	

 

그리고 sql을 작성해서 db에 보내줄 내용을 MemberDTO에 작성.

public int insertMessage(MessageDTO dto) {
	
	int cnt = 0;
	getConnection();
	String sql = "insert into web_message values(msg_num.nextval,?,?,?,sysdate)";
	try {
		psmt = conn.prepareStatement(sql);
		psmt.setString(1, dto.getSend_name());
		psmt.setString(2, dto.getReceive_email());
		psmt.setString(3, dto.getContent());
		
		cnt = psmt.executeUpdate();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		close();
	}
	return cnt;
}

결과 확인 :

4번째 라인은 코드 파악을 덜한 상태에서 입력했기에 시퀀스와 day가 빠진 상태이다.

 

728x90
반응형
Comments