프로그래밍/JSP Servlet

JSP/Servlet – 모델2로 웹애플리케이션 설계하기

가카리 2016. 4. 29. 21:14
반응형

 

JSP/Servlet – 모델2로 웹애플리케이션 설계하기

 

모델 1방식은 jsp에서 모든 것을 처리했다면 모델 2에서는 복잡한 것은 서블릿에서 처리하고 사용자에게 보여주는 부분만

 

jsp로 처리합니다. (모델 1과 모델 2의 차이점 링크 참조)

 

다음 예제는 간단한 게시판목록을 보여주는 웹페이지입니다.

 

 

이번 예제를 위해서 JSTL 라이브러리와 MYSQL CONNECTOR 그리고 데이터베이스 커넥터풀 사용을 위한 라이브러리가 필요합니다.

 

데이터 베이스는 이전 예제에서 썼던 것을 사용합니다. (모델1로 웹애플리케이션 설계하기)

 

게시판 글을 위한 sql 문

 

insert into bbs (seqno, title, content, writer, wdate, wtime) values (4, '축하합니다.!', '드디어 오픈하셨군요. 3등~', 'spider', '2009/11/24', '13:30:12');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (5, '4등!!!', '인터넷 구매는 어디서 하나요?', 'jb007', '2009/11/24', '13:31:29');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (6, '5등!', '이 다음은 순위권 밖!!', 'kirk', '2009/11/24', '13:31:55');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (7, '6등!!!', '앗! 언제 오픈한 건가요?', 'shadow', '2009/11/24', '13:32:09');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (8, '6등~~', '6등~~~~~~~~~~~ 아닌가??', 'colonel', '2009/11/24', '13:32:15');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (9, '등수놀이 좀 그만합시다.', '***8등*** ┗(-_- )┓', 'woods', '2009/11/24', '13:34:20');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (10, '9등', '^.^', 'apache', '2009/11/24', '13:35:03');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (11, '10등 -----------절취선-----------', '10등.', 'amadeus', '2009/11/24', '13:37:15');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (12, '~~~11등~~~ v(^0^)v', 'o(*^-^*)o', 'jj8539', '2009/11/24', '13:39:00');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (13, '(/^o^)/', '야호~~', 'neptune', '2009/11/24', '13:42:59');

 

 

BBSList.java

기본적인 데이터를 저장하기 위한 자바빈 클래스입니다.

 

package web;

 

import java.sql.*;

import java.util.ArrayList;

 

public class BBSList {

    private ArrayList<Integer> seqNoList = new ArrayList<Integer>();

    private ArrayList<String> titleList = new ArrayList<String>();

    private ArrayList<String> writerList = new ArrayList<String>();

    private ArrayList<Date> dateList = new ArrayList<Date>();

    private ArrayList<Time> timeList = new ArrayList<Time>();

    private boolean lastPage = false;

    

    public BBSList(){

        

    }

    public void setSeqNo(int index, Integer seqNo){

        this.seqNoList.add(index, seqNo);

    }

    public void setTitle(int index, String title){

        this.titleList.add(index, title);

    }

    public void setWriter(int index, String writer){

        this.writerList.add(index, writer);

    }

    public void setDate(int index, Date date){

        this.dateList.add(index, date);

    }

    public void setTime(int index, Time time){

        this.timeList.add(index, time);

    }

    public void setLastPage(boolean lastPage){

        this.lastPage = lastPage;

    }

    public Integer[] getSeqNo(){

        return seqNoList.toArray(new Integer[seqNoList.size()]);

    }

    public String[] getTitle(){

        return titleList.toArray(new String[titleList.size()]);

    }

    public String[] getWriter(){

        return writerList.toArray(new String[writerList.size()]);

    }

    public Date[] getDate(){

        return dateList.toArray(new Date[dateList.size()]);

    }

    public Time[] getTime(){

        return timeList.toArray(new Time[timeList.size()]);

    }

    public boolean isLastPage(){

        return lastPage;

    }

    public int getListSize(){//게시글의 수를 리턴하는 메소드

        return seqNoList.size();

    }

}

 

 

BBSListServlet.java

데이터베이스에 접속 후 데이터를 가져온 다음 그것을 BBS_LIST 라는 애트리뷰트에 저장하는 역할을 합니다.

모든 할 일을 끝내고 마지막으로 JSP파일을 호출합니다.

package web;

 

import java.io.IOException;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

 

import javax.naming.Context;

import javax.naming.InitialContext;

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 javax.sql.DataSource;

 

/**

* Servlet implementation class BBSListServlet

*/

@WebServlet("/BBSListServlet")

public class BBSListServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

 

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        String strUpperSeqNo = request.getParameter("LAST_SEQ_NO");//파라미터를 가져옴

        int upperSeqNo;

        

        if(strUpperSeqNo == null)//값이 없으면

            upperSeqNo = Integer.MAX_VALUE;//최대값

        else

            upperSeqNo = Integer.parseInt(strUpperSeqNo);

        BBSList list = readDB(upperSeqNo);

        request.setAttribute("BBS_LIST", list);//디비에서 가져와서 애트리뷰트에 저장

        RequestDispatcher dispatcher = request.getRequestDispatcher("BBSListView.jsp");//JSP파일로 이동하기 위한

        dispatcher.forward(request, response);

    }

    //데이터베이스 접속후 데이터를 가져오기위한 메소드

    private BBSList readDB(int upperSeqNo) throws ServletException{

        BBSList list = new BBSList();

        Connection conn = null;

        Statement stmt = null;

        try{

            //데이터베이스 커넥션풀에 접속

            Context context = new InitialContext();

         DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/wdbpool");

         conn = ds.getConnection();

            

            if(conn == null)

                throw new Exception("데이터베이스 연결 실패");

            stmt = conn.createStatement();

            //쿼리문을 날려서 데이터를 가져옴

            ResultSet rs = stmt.executeQuery("select * from bbs where seqNo < " + upperSeqNo +

                    " order by seqno desc;");

            for(int cnt = 0; cnt < 5; cnt++){    

                if(!rs.next())

                    break;

                list.setSeqNo(cnt, rs.getInt("seqNo"));

                list.setTitle(cnt, toUnicode(rs.getString("title")));

                list.setWriter(cnt, toUnicode(rs.getString("writer")));

                list.setDate(cnt, rs.getDate("wdate"));

                list.setTime(cnt, rs.getTime("wtime"));

            

            }

            if(!rs.next())

                list.setLastPage(true);

        }catch(Exception e){

            throw new ServletException(e);

        }

        finally{

            try{

                stmt.close();

            }catch(Exception ignored){

                

            }

            try{

                conn.close();

            }

            catch(Exception ignored){

                

            }

        }

        return list;

    }

    //한글출력이 잘되게 유니코드로 바꿔주는 메소드

    private String toUnicode(String str){

        if(str == null)

            return null;

        try{

            byte[] b = str.getBytes("ISO-8859-1");

            return new String(b);

        }

        catch(java.io.UnsupportedEncodingException uee){

            System.out.println(uee.getMessage());

            return null;

        }

    

    }

 

}

 

BBSListView.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    <H4>게시판 목록 출력</H4>

    <TABLE border=1>

        <c:forEach var="cnt" begin="0" end="${BBS_LIST.listSize - 1 }">

            <TR>

                <TD>${BBS_LIST.seqNo[cnt] }</TD>

                <TD>${BBS_LIST.title[cnt] }</TD>

                <TD>${BBS_LIST.writer[cnt] }</TD>

                <TD>${BBS_LIST.date[cnt] }</TD>

                <TD>${BBS_LIST.time[cnt] }</TD>            

            </TR>

        </c:forEach>

    </TABLE>

    <c:if test="${!BBS_LIST.lastPage }">

        <A href='bbs-list?LAST_SEQ_NO=${BBS_LIST.seqNo[BBS_LIST.listSize - 1] }'>다음 페이지</A>

    </c:if>

</body>

</html>

 

web.xml

서블릿 클래스를 등록하기 위한 web.xml입니다.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

<display-name>ch13_jsp_model2</display-name>

<servlet>

<servlet-name>bbs-list-servlet</servlet-name>

<servlet-class>web.BBSListServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>bbs-list-servlet</servlet-name>

<url-pattern>/bbs-list</url-pattern>

</servlet-mapping>

</web-app>

 

context.xml

<Context>

 

<Resource name="jdbc/wdbpool"

auth="Container"

type="javax.sql.DataSource"

url="jdbc:mysql://localhost:3306/webdb"

username="root"

password="apmsetup"

driverClassName="com.mysql.jdbc.Driver"

maxActive="10"

maxIdle="2"

/>

 

</Context>

 

 

실행 화면

서블릿 클래스의 URL을 입력합니다.

다음페이지를 누르면 아래와 같이 출력됩니다.

 

반응형