'WEB/Servlet'에 해당되는 글 1건


① 소스내용


package dept;

 

import java.io.*;

import java.sql.*;

 

import javax.servlet.*;

import javax.servlet.http.*;

import javax.sql.*;

 

import common.*;

 

public class DeptServlet extends HttpServlet {

    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setCharacterEncoding("euc-kr");

        PrintWriter out = response.getWriter();

       

        // 1. DB 연결

        Connection conn = null;

        Statement stmt = null;

        ResultSet rs = null;

       

        try {

            // InitListener에서 가지고 오기

            DataSource ds = (DataSource)getServletContext().getAttribute("ds");

           

            conn = ds.getConnection();

            stmt = conn.createStatement();

            rs = stmt.executeQuery("select * from dept");

            // select * from dept

            // 2. 쿼리문 날려서 결과를 가져온다.

           

            // 3. 브라우저에 결과를 출력한다.

            out.println("<table border='5' align='center' width='500' bordercolor='red'>");

            out.println("<tr>");

            out.println("<th>번호</th>");

            out.println("<th>deptno</th>");

            out.println("<th>deptname</th>");                        

            out.println("<th>loc</th>");

            out.println("</tr>");

            int i=1;

            while(rs.next()){

               out.println("<tr align='center' color='red'>");

               out.println("<th>"+i+"</th>");              

               out.println("<td>"+rs.getString(1)+"</td>");                           

               out.println("<td>"+rs.getString(2)+"</td>");                           

               out.println("<td>"+rs.getString(3)+"</td>");

               out.println("</tr>");

               i++;

            }

            out.print("</table>");

        }catch (SQLException e) {

                e.printStackTrace();

        } finally {

            try {

                if(rs != null)rs.close();

            } catch (SQLException e) {

                e.printStackTrace();

            } try {

                if(stmt != null)stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            } try {

                if(conn != null)conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }   

    }

}

 


② 실행결과


블로그 이미지

모데스티

,