ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JSP] 웹어플리케이션의 일반적인 구성 및 방명록 구현
    프로그래밍/JAVA 2015. 7. 28. 22:15
    반응형

    JSP만을 이용하는 경우의 문제

    - 동일한 로직을 수행하는 코드가 중복될 가능성이 높음

    - 문제점 : 기능 변경 발생 시 여러 코드에 동일한 수정 반영해 주어야 함

    - 누락될 가능성 발생 -> 버그 발생 가능성 높음


    클래스를 이용한 중복 제거

    - 클래스를 이용해서 중복된 코드를 한 곳으로 분리

    - 화면 요청 처리하는 JSP와 실제 로직을 수행하는 클래스로 분리하는것이 일반적인 구성




    웹 어플리케이션의 일반적인 구성

    - Service 클래스 : 사용자의 요청을 처리하는 기능을 제공


    오늘의 코드


    package util;


    import java.sql.Connection;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.sql.Statement;


    public class JdbcUtil {

    public static void close(ResultSet rs) {

    if (rs != null) {

    try {

    rs.close();

    } catch (SQLException ex) {

    }

    }

    }


    public static void close(Statement stmt) {

    if (stmt != null) {

    try {

    stmt.close();

    } catch (SQLException ex) {

    }

    }

    }


    public static void close(Connection conn) {

    if (conn != null) {

    try {

    conn.close();

    } catch (SQLException ex) {

    }

    }

    }


    public static void rollback(Connection conn) {

    if (conn != null) {

    try {

    conn.rollback();


    } catch (SQLException ex) {

    }

    }

    }

    }


    package util;


    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.SQLException;


    public class ConnectionProvider {

    public static Connection getConnection() throws SQLException {

    return DriverManager.getConnection("jdbc:apache:commons:dbcp:/pool");

    }


    }



    package util;

    public class Message {

    private int id;
    private String guestName;
    private String password;
    private String message;

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public String getGuestName() {
    return guestName;
    }

    public void setGuestName(String guestName) {
    this.guestName = guestName;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    public String getMessage() {
    return message;
    }

    public void setMessage(String message) {
    this.message = message;
    }

    public boolean hasPassword() {
    return password != null && !password.isEmpty();
    }
    }

    package util;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.List;

    import util.Message;
    import util.JdbcUtil;

    public abstract class MessageDao {
    public abstract int insert(Connection conn, Message message) throws SQLException;

    public Message select(Connection conn, int messageId) throws SQLException {
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
    pstmt = conn.prepareStatement("select * from guestbook_message0614 where message_id=?");
    pstmt.setInt(1, messageId);
    rs = pstmt.executeQuery();
    if (rs.next()) {
    return makeMessageFromResultSet(rs);
    } else {
    return null;
    }
    } finally {
    JdbcUtil.close(rs);
    JdbcUtil.close(pstmt);
    }
    }

    protected Message makeMessageFromResultSet(ResultSet rs) throws SQLException {
    Message message = new Message();
    message.setId(rs.getInt("message_id"));
    message.setGuestName(rs.getString("guest_name"));
    message.setPassword(rs.getString("password"));
    message.setMessage(rs.getString("message"));
    return message;
    }

    public int selectCount(Connection conn) throws SQLException {
    Statement stmt = null;
    ResultSet rs = null;
    try {
    stmt = conn.createStatement();
    rs = stmt.executeQuery("select count(*) from guestbook_message0614");
    rs.next();
    return rs.getInt(1);
    } finally {
    JdbcUtil.close(rs);
    JdbcUtil.close(stmt);
    }
    }

    public abstract List<Message> selectList(Connection conn, int firstRow, int endRow) throws SQLException;

    public int delete(Connection conn, int messageId) throws SQLException {
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
    pstmt = conn.prepareStatement("delete from guestbook_message0614 where message_id = ?");
    pstmt.setInt(1, messageId);
    return pstmt.executeUpdate();
    } finally {
    JdbcUtil.close(rs);
    JdbcUtil.close(pstmt);
    }
    }

    }

    package util;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    import util.MessageDao;
    import util.Message;
    import util.JdbcUtil;

    public class OracleMessageDao extends MessageDao {

    public int insert(Connection conn, Message message) throws SQLException {
    PreparedStatement pstmt = null;
    try {
    pstmt = conn.prepareStatement("insert into guestbook_message "
    + " (message_id, guest_name, password, message) " + " values (message_id_seq.NEXTVAL, ?, ?, ?)");
    pstmt.setString(1, message.getGuestName());
    pstmt.setString(2, message.getPassword());
    pstmt.setString(3, message.getMessage());
    return pstmt.executeUpdate();
    } finally {
    JdbcUtil.close(pstmt);
    }
    }

    public List<Message> selectList(Connection conn, int firstRow, int endRow) throws SQLException {
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
    pstmt = conn.prepareStatement("select message_id, guest_name, password, message from ( "
    + "    select rownum rnum, message_id, guest_name, password, message from ( "
    + "        select * from guestbook_message0614 m order by m.message_id desc "
    + "    ) where rownum <= ? " + ") where rnum >= ?");

    pstmt.setInt(1, endRow);
    pstmt.setInt(2, firstRow);
    rs = pstmt.executeQuery();
    if (rs.next()) {
    List<Message> messageList = new ArrayList<Message>();
    do {
    messageList.add(super.makeMessageFromResultSet(rs));
    } while (rs.next());
    return messageList;
    } else {
    return Collections.emptyList();
    }
    } finally {
    JdbcUtil.close(rs);
    JdbcUtil.close(pstmt);
    }
    }

    }

    package util;


    import util.OracleMessageDao;


    public class MessageDaoProvider {

    private static MessageDaoProvider instance = new MessageDaoProvider();


    public static MessageDaoProvider getInstance() {

    return instance;

    }


    private MessageDaoProvider() {

    }


    private OracleMessageDao oracleDao = new OracleMessageDao();

    private String dbms;


    void setDbms(String dbms) {

    this.dbms = dbms;

    }


    public MessageDao getMessageDao() {

    if ("oracle".equals(dbms)) {

    return oracleDao;

    }

    return null;

    }

    }



    package util;


    import util.OracleMessageDao;


    public class MessageDaoProvider {

    private static MessageDaoProvider instance = new MessageDaoProvider();


    public static MessageDaoProvider getInstance() {

    return instance;

    }


    private MessageDaoProvider() {

    }


    private OracleMessageDao oracleDao = new OracleMessageDao();

    private String dbms;


    void setDbms(String dbms) {

    this.dbms = dbms;

    }


    public MessageDao getMessageDao() {

    if ("oracle".equals(dbms)) {

    return oracleDao;

    }

    return null;

    }

    }



    package util;


    public class ServiceException extends Exception {

    public ServiceException(String message, Exception cause) {

    super(message, cause);

    }


    public ServiceException(String message) {

    super(message);

    }

    }


    package util;


    import java.util.List;


    public class MessageListView {

    private int messageTotalCount;

    private int currentPageNumber;

    private List<Message> messageList;

    private int pageTotalCount;

    private int messageCountPerPage;

    private int firstRow;

    private int endRow;


    public MessageListView(List<Message> messageList, int messageTotalCount, int currentPageNumber,

    int messageCountPerPage, int startRow, int endRow) {

    this.messageList = messageList;

    this.messageTotalCount = messageTotalCount;

    this.currentPageNumber = currentPageNumber;

    this.messageCountPerPage = messageCountPerPage;

    this.firstRow = startRow;

    this.endRow = endRow;


    calculatePageTotalCount();

    }


    private void calculatePageTotalCount() {

    if (messageTotalCount == 0) {

    pageTotalCount = 0;

    } else {

    pageTotalCount = messageTotalCount / messageCountPerPage;

    if (messageTotalCount % messageCountPerPage > 0) {

    pageTotalCount++;

    }

    }

    }


    public int getMessageTotalCount() {

    return messageTotalCount;

    }


    public int getCurrentPageNumber() {

    return currentPageNumber;

    }


    public List<Message> getMessageList() {

    return messageList;

    }


    public int getPageTotalCount() {

    return pageTotalCount;

    }


    public int getMessageCountPerPage() {

    return messageCountPerPage;

    }


    public int getFirstRow() {

    return firstRow;

    }


    public int getEndRow() {

    return endRow;

    }


    public boolean isEmpty() {

    return messageTotalCount == 0;

    }


    }





    package util;


    import java.sql.Connection;

    import java.sql.SQLException;

    import java.util.Collections;

    import java.util.List;


    import util.MessageDao;

    import util.MessageDaoProvider;

    import util.Message;

    import util.MessageListView;

    import util.JdbcUtil;

    import util.ConnectionProvider;


    public class GetMessageListService {

    private static GetMessageListService instance = new GetMessageListService();


    public static GetMessageListService getInstance() {

    return instance;

    }


    private GetMessageListService() {

    }


    private static final int MESSAGE_COUNT_PER_PAGE = 3;


    public MessageListView getMessageList(int pageNumber) throws ServiceException {

    Connection conn = null;

    int currentPageNumber = pageNumber;

    try {

    conn = ConnectionProvider.getConnection();

    MessageDao messageDao = MessageDaoProvider.getInstance().getMessageDao();


    int messageTotalCount = messageDao.selectCount(conn);


    List<Message> messageList = null;

    int firstRow = 0;

    int endRow = 0;

    if (messageTotalCount > 0) {

    firstRow = (pageNumber - 1) * MESSAGE_COUNT_PER_PAGE + 1;

    endRow = firstRow + MESSAGE_COUNT_PER_PAGE - 1;

    messageList = messageDao.selectList(conn, firstRow, endRow);

    } else {

    currentPageNumber = 0;

    messageList = Collections.emptyList();

    }

    return new MessageListView(messageList, messageTotalCount, currentPageNumber, MESSAGE_COUNT_PER_PAGE,

    firstRow, endRow);

    } catch (SQLException e) {

    throw new ServiceException("메시지 목록 구하기 실패 : " + e.getMessage(), e);

    } finally {

    JdbcUtil.close(conn);

    }

    }

    }



    package util;


    import java.sql.Connection;

    import java.sql.SQLException;


    import util.MessageDao;

    import util.MessageDaoProvider;

    import util.Message;

    import util.JdbcUtil;

    import util.ConnectionProvider;


    public class WriteMessageService {

    private static WriteMessageService instance = new WriteMessageService();


    public static WriteMessageService getInstance() {

    return instance;

    }


    private WriteMessageService() {

    }


    public void write(Message message) throws ServiceException {

    Connection conn = null;

    try {

    conn = ConnectionProvider.getConnection();

    MessageDao messageDao = MessageDaoProvider.getInstance().getMessageDao();

    messageDao.insert(conn, message);

    } catch (SQLException e) {

    throw new ServiceException("메시지 등록 실패 : " + e.getMessage(), e);

    } finally {

    JdbcUtil.close(conn);

    }

    }

    }


    package util;


    public class MessageNotFoundException extends Exception {

    public MessageNotFoundException(String message) {

    super(message);

    }

    }



    package util;


    public class InvalidMessagePasswordException extends Exception{


    }



    package util;


    import java.sql.Connection;

    import java.sql.SQLException;


    import util.MessageDao;

    import util.MessageDaoProvider;

    import util.Message;

    import util.JdbcUtil;

    import util.ConnectionProvider;


    public class DeleteMessageService {

    private static DeleteMessageService instance = new DeleteMessageService();


    public static DeleteMessageService getInstance() {

    return instance;

    }


    private DeleteMessageService() {

    }


    public void deleteMessage(int messageId, String password)

    throws ServiceException, InvalidMessagePasswordException, MessageNotFoundException {

    Connection conn = null;

    try {

    conn = ConnectionProvider.getConnection();

    conn.setAutoCommit(false);


    MessageDao messageDao = MessageDaoProvider.getInstance().getMessageDao();

    Message message = messageDao.select(conn, messageId);

    if (message == null) {

    throw new MessageNotFoundException("메시지가 없습니다 : " + messageId);

    }

    if (!message.hasPassword()) {

    throw new InvalidMessagePasswordException();

    }

    if (!message.getPassword().equals(password)) {

    throw new InvalidMessagePasswordException();

    }

    messageDao.delete(conn, messageId);


    conn.commit();

    } catch (SQLException ex) {

    JdbcUtil.rollback(conn);

    throw new ServiceException("삭제 처리 중 에러가 발생했습니다" + ex.getMessage(), ex);

    } catch (InvalidMessagePasswordException ex) {

    JdbcUtil.rollback(conn);

    throw ex;

    } catch (MessageNotFoundException ex) {

    JdbcUtil.rollback(conn);

    throw ex;

    } finally {

    if (conn != null) {

    try {

    conn.setAutoCommit(false);

    } catch (SQLException e) {

    }

    JdbcUtil.close(conn);

    }

    }


    }

    }

    반응형

    '프로그래밍 > JAVA' 카테고리의 다른 글

    [JSP] 표현 언어(Expression Language)  (0) 2015.07.29
    [JAVA] 객체지향 프로그래밍(3)  (0) 2015.07.28
    [JSP] JSP 기본 (1)  (0) 2015.07.13
    [JAVA] IO Stream (1)  (0) 2015.07.08
    [JAVA] 객체지향 프로그래밍 (2)  (0) 2015.07.08

    댓글

Designed by Tistory.