프로그래밍/JSP Servlet

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

가카리 2016. 4. 21. 21:17
반응형

 

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

 

모델 1은 JSP 페이지와 자바빈 클래스를 이용해서 웹 애플리케이션을 모듈화하는 설계 모델입니다.

 

모델 2는 Servlet으로 로직이 구현되고 JSP에서 뷰를 담당합니다.

 

(모델1 과 모델 2의 차이점 링크 참조)

 

그러면 모델 1로 간단히 데이터베이스의 값을 가져오는 예제를 만들어 봅시다.

 

먼저 데이터 베이스를 만들어야합니다.

 

    create database webdb;

    use webdb;

 

다음 다음과 같은 쿼리문으로 테이블을 만들어 줍니다.

 

create table bbs (

seqno integer(8) not null,

title varchar(50) not null,

content varchar(500) not null,

writer varchar(20) not null,

wdate date not null,

wtime time not null,

primary key(seqno)

);

 

그리고 insert문으로 몇 개의 쿼리문을 넣어줍니다.

 

insert into bbs (seqno, title, content, writer, wdate, wtime) values (1, '게시판 오픈!', '많이 이용해주세요~', 'spider', '2009/11/24', '13:20:15');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (2, '1등이다!', '1등이다', 'batman', '2009/11/24', '13:25:30');

insert into bbs (seqno, title, content, writer, wdate, wtime) values (3, '2등이다!', '2등이다', 'rose', '2009/11/24', '13:27:19');

 

 

위와 같이 lib폴더에는 데이터베이스 커넥션풀을 이용하기 위한 collections, dbcp2, logging, pool2 라이브러리를 구성하고 mysql사용을 위한 커넥터 라이브러리를

 

복사해줍니다.

 

자바빈 클래스 구현

 

BBSItem.java

 

package web;

 

import java.sql.Connection;

import java.sql.Date;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.Time;

 

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.servlet.ServletException;

import javax.sql.DataSource;

 

public class BBSItem {

    private int seqNo;        //순번

    private String title;    //제목

    private String content;    //내용

    private String writer; //작성자

    private Date date;

    private Time time;

    //자바빈 클래스 작성

    public BBSItem(){

        

    }

    public void setSeqNo(int seqNo){

        this.seqNo = seqNo;

    }

    public String getTitle(){

        return toUnicode(title);

    }

    public String getContent(){

        return toUnicode(content);

    }

    public String getWriter(){

        return toUnicode(writer);

    }

    public Date getDate(){

        return date;

    }

    public Time getTime(){

        return time;

    }

    public void readDB() throws ServletException{

        //데이터베이스로부터 게시글을 읽는 메소드

        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 = '" + seqNo + "';");

            if(rs.next()){

                title = rs.getString("title");

                content = rs.getString("content");

                writer = rs.getString("writer");

                date = rs.getDate("wdate");

                time = rs.getTime("wtime");

            }

        }catch(Exception e){

            throw new ServletException(e);

        }

        finally{

            try{

                stmt.close();

            }catch(Exception ignored){

                

            }

            try{

                conn.close();

            }

            catch(Exception ignored){

                

            }

        }

    }

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

    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;

        }

    }

}

 

 

데이터베이스값 출력을 위한 jsp 파일

 

ReadDB.jsp

 

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

pageEncoding="EUC-KR"%>

<jsp:useBean id="bbsItem" class="web.BBSItem"/>

<jsp:setProperty name="bbsItem" property="seqNo" value="${param.SEQ_NO }"/>

<% bbsItem.readDB(); %>

 

<!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>

    게시글 읽고 데이터베이스 출력<BR>

    <jsp:getProperty name="bbsItem" property="title"/><BR>

    <jsp:getProperty name="bbsItem" property="writer"/><BR>

    <jsp:getProperty name="bbsItem" property="date"/><BR>

    <jsp:getProperty name="bbsItem" property="time"/><BR>

    ---------------------------------------------------<BR>

    <jsp:getProperty name="bbsItem" property="content"/><BR>

</body>

</html>

 

마지막 데이터베이스 커넥션풀 접속을 위한 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>

 

실행 화면

다음과 같이 데이터베이스에서 값을 잘 읽어옴을 알 수 있습니다. 여기서 유의할 점은 parameter SEQ_NO를 1로 줬다는 점입니다.

만약 SEQ_NO를 2로 바꾸면 출력되는 값이 바뀌게됩니다.

 

반응형