프로그래밍/JSP Servlet

JSP/Servlet – 데이터베이스에서 값 읽어오기

가카리 2016. 4. 10. 20:17
반응형

 

JSP/Servlet – 데이터베이스에서 값 읽어오기

 

mysql 을 설치하고 먼저 데이터 베이스를 만들어봅시다.

 

    create database webdb;

 

그 다음 테이블을 만듭니다.

 

create table goodsinfo (

code char(5) not null,

title varchar(50) not null,

writer varchar(20),

price int(8) not null,

primary key(code)

);

를 치면 다음과 같이 desc 명령어로 테이블을 확인할 수 있습니다.

 

마지막으로 데이터를 한 개 넣어 봅시다.

 

insert into goodsinfo (code, title, writer, price) values ('1', 'jsp programming', 'gakari', 20000);

 

select문으로 보니 데이터베이스에 값이 제대로 들어간 것을 볼 수 있습니다.

 

다음으로 예제를 작성해봅시다.

 

 

위와 같이 lib에는 반드시 JDBC 드라이버를 설치해야합니다.

 

GoodsInfoReader.jsp

<%@page import="java.io.UnsupportedEncodingException" errorPage="DBError.jsp"%>

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

pageEncoding="EUC-KR"%>

<%@page import="java.sql.*" %>

<%

    String code = request.getParameter("code");

    Connection conn = null;

    Statement stmt = null;

    try{

        Class.forName("com.mysql.jdbc.Driver");//JDBC 드라이버를 대표하는 클래스 이름을 넘겨줌

      

        //DB 연결을 위한 주소 ID PW

        conn = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/webdb", "root1", "apmsetup");

        if(conn == null)

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

        stmt = conn.createStatement();//데이터베이스 값을 읽어오기위한 Statement 객체 만들기

        //아래는 쿼리문을 만드는 과정

        ResultSet rs = stmt.executeQuery("select * from goodsinfo where code = '" + code + "';");

        

        //실제 데이터를 가져옴

        if(rs.next()){

            String title = rs.getString("title");

            String writer = rs.getString("writer");

            int price = rs.getInt("price");

            request.setAttribute("CODE", code);//다음페이지에서 출력하기 위해 애트리뷰트에 넣어줍니다.

            request.setAttribute("TITLE", toUnicode(title));

            request.setAttribute("WRITER", toUnicode(writer));

            request.setAttribute("PRICE", new Integer(price));

        }

    }

    finally{

        try{

            stmt.close();//Statement 객체를 닫음

        }catch(Exception ignored){

        }

        

        try{

            conn.close();//데이터 베이스 연결 종료

        }

        catch(Exception ignored){

        }

        

    }

    

    RequestDispatcher dispatcher = request.getRequestDispatcher("GoodsInfoViewer.jsp");

    dispatcher.forward(request, response);

%>

<%!

    private String toUnicode(String str){//ISO-8859-1 문자열을 Unicode 문자열로 변환

    //이것을 안쓰면 한글이 깨져보임

        try{

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

            return new String(b);

        }catch(UnsupportedEncodingException uee){

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

            return null;

        }

    }

 

%>

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

 

</body>

</html>

 

GoodsInfoViewer.jsp

 

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

pageEncoding="EUC-KR"%>

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

    코드 : ${CODE }<BR>

    제목 : ${TITLE }<BR>

    저자 : ${WRITER }<BR>

    가격 : ${PRICE }

</body>

</html>

 

DBError.jsp

 

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

pageEncoding="EUC-KR" isErrorPage="true" %>

<%

    response.setStatus(200);

%>

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

    에러 메시지 : <%= exception.getMessage() %>

</body>

</html>

 

실행 화면

아래와 같이 code=1로 하면 정상 출력됩니다.

하지만 데이터베이스 id를 잘못 입력하면 다음과 같이 뜹니다.

 

반응형