JSP - Maven - Message (Send message)

화이티 ·2023년 12월 21일
0

JSP

목록 보기
6/12
<%@page import="com.smhrd.model.Message"%>
<%@page import="com.smhrd.model.Member"%>
<%@page import="com.smhrd.model.MessageDAO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<section> <!-- Q11. 메시지 보내기 기능(메시지는 계속 확인하기 위해서 DB에 저장!) -->

			<!-- 다른 사람의 DB에 메시지 저장해보기! -->
			<form action="MessageService" method="post">
				<div class="field half first">
					<label for="name">Name</label> <input type="text" id="name"
						placeholder="보내는 사람 이름" name="sender" />
				</div>
				<div class="field half">
					<label for="email">Email</label> <input type="text" id="email"
						placeholder="받는 사람 이메일" name="recipient" />
				</div>

				<div class="field">
					<label for="message">Message</label>
					<textarea id="message" rows="6" name="message"></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>
<!-- Q13. table형태로 나한테 온 메시지만 가져와서 보여주기
											 번호, 보낸사람, 내용, 시간 -->

				<!--  message조회하기 receipient = login email-->
				<c:if test="${loginMember!= null }">
					<c:set var="messages"
						value="${MessageDAO.allMessage(loginMember.email) }">
					</c:set>
				</c:if>

				<table>
					<tr>
						<th>번호</th>
						<th>보낸는 사람 🌴🌵</th>
						<th>내용 🍓🍓</th>
						<th>시간 🍁🍁</th>
					</tr>
					<c:forEach var="m" items="${messages }" varStatus="s">
						<tr>
							<td>${s.count}</td>
							<td>${m.sender}</td>
							<td>${m.message}</td>
							<td>${m.m_date}</td>
						</tr>
					</c:forEach>
				</table>
<form action="MessageService" method="post">
				<div class="field half first">
					<label for="name">Name</label> <input type="text" id="name"
						placeholder="보내는 사람 이름" name="sender" />
				</div>
				<div class="field half">
					<label for="email">Email</label> <input type="text" id="email"
						placeholder="받는 사람 이메일" name="recipient" />
				</div>

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

Message 변수 declaration

package com.smhrd.model;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
@AllArgsConstructor
@NoArgsConstructor

@Getter
@ToString 
public class Message {
	private int num;
	 private String sender;
	 private String recipient;
	private String message;
	private String m_date;
	
}

Message DAO

package com.smhrd.model;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.smhrd.database.SqlSessionManager;

public class MessageDAO {
	// 세션을 생성해 줄 수 있는 factory 생성
		static SqlSessionFactory sqlSessionFactory = SqlSessionManager.getSqlSession();
		//connnection.close, sql문 실행
	
//메시지 보내기 기능
		public int sendMessage(Message vo) {
			 SqlSession sqlSession = sqlSessionFactory.openSession(true);
			int cnt = 0;
			try {
				cnt = sqlSession.insert("com.smhrd.database.MessageMapper.sendMessage", vo);

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				sqlSession.close();

			}
			return cnt;

		}
//message 조회 기능
		public static List<Message> allMessage(String email) {
			 SqlSession sqlSession = sqlSessionFactory.openSession(true);
			List<Message> messages =null;
			try { 
				messages = sqlSession.selectList("com.smhrd.database.MessageMapper.allMessage",email);
			}catch(Exception e) {
				e.printStackTrace();
			}finally {
				sqlSession.close();
			}
		return messages;
		}
}

Message Service

package com.smhrd.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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.smhrd.model.Message;
import com.smhrd.model.MessageDAO;

@WebServlet("/MessageService")
public class MessageService extends HttpServlet {
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		 String sender = request.getParameter("sender");
		 String recipient = request.getParameter("recipient");
		 String message = request.getParameter("message");
		 System.out.println("[MessageService]");
		 System.out.println("Sender: " + sender);
		 System.out.println("Recipient: " + recipient);
		 System.out.println("Message: " + message);
		 
		 Message vo = new Message(0,sender,recipient, message, null);
		 
		 int cnt = new MessageDAO().sendMessage(vo);
		 System.out.println("cnt : "+cnt);
		 if (cnt >0) {
			 System.out.println("Send message successfully");
			
			 request.setAttribute("message", message);
			
			
		 }else {
			 System.out.println("send message fail");
			
		 }
		 response.sendRedirect("Main.jsp");
	}
	}

Message Mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  
  <mapper namespace ="com.smhrd.database.MessageMapper">
  <insert id="sendMessage" parameterType = "Message">
  
  insert into web_message values(num_board.nextval,#{sender},#{recipient},#{message},sysdate)
  </insert>
 <select id = "allMessage" resultType= "Message">
select * from web_message where recipient = #{email}

</select>
  </mapper>

my batis - config

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 2. add my batis-config.xml: my batis의 환뎡설정 담당(중요한 파일)
	3. db.properties 만들기
		: db연결보들을 가지고 있는 파일 -> 공백 주의할 것 -->
		<properties resource="com/smhrd/database/db.properties"> </properties>
 
 <typeAliases>
 	<typeAlias type="com.smhrd.model.Member" alias ="Member"/>
 <typeAlias type="com.smhrd.model.Board" alias ="Board"/>
  <typeAlias type="com.smhrd.model.Message" alias ="Message"/>
 </typeAliases>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/smhrd/database/MemberMapper.xml"/>
     <mapper resource="com/smhrd/database/BoardMapper.xml"/>
      <mapper resource="com/smhrd/database/MessageMapper.xml"/>
  </mappers>
</configuration>
profile
열심히 공부합시다! The best is yet to come! 💜

0개의 댓글