目次へ

解答例 - 実習課題2 - 3.サーブレットの基本2

(実習課題2)

実習課題1を改良しなさい。

  • それぞれのメソッドの先頭で、必ずログに出力を行うこと。
  • 例外が発生したときにも、ログに出力を行なうようにする事。
  • わざと例外が発生する状況にし、例外がどのようにログに出力されるか確認すること。

解答例

/*
 * DisplayDbTableServlet.java TECHSCORE Java Servlet3章 実習課題2
 * 
 * Copyright (c) 2004 Four-Dimensional Data, Inc.
 */
package com.techscore.servlet.chapter3.exercise2;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DisplayDbTableServlet extends HttpServlet {

    private static final String[] PARAMS = { "sql1", "sql2", "sql3" };

    private String[] sqls = new String[PARAMS.length];

    private String url = null;

    private String username = null;

    private String password = null;

    private String driverClassName = null;

    private boolean isEmptySqls() {
        for (int i = 0; i < sqls.length; i++) {
            if (sqls[i] == null) {
                return true;
            }
        }
        return false;
    }

    private Connection getConnection() throws SQLException {
        this.log("getConnection() run");
        Connection conn = null;
        try {
            Class.forName(driverClassName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            this.log("getConnection()", e);
        }
        return conn;
    }

    private String getHtmlTable(HttpServletRequest request,
            HttpServletResponse response, Connection conn, String sql)
            throws SQLException {
        this.log("readDb() run");
        Statement statement = conn.createStatement();
        ResultSet result = statement.executeQuery(sql);
        StringBuffer buffer = new StringBuffer();
        buffer.append("<table border=\"1\">");
        while (result.next()) {
            buffer.append("<tr><td>").append(result.getInt(1)).append("</td>");
            buffer.append("<td>").append(result.getString(2)).append("</td>");
            buffer.append("<td>").append(result.getString(3)).append("</td>");
            buffer.append("<td>").append(result.getInt(4)).append("</td></tr>");
        }
        buffer.append("</table>");
        result.close();
        statement.close();
        return buffer.toString();
    }

    private String getSuitableSql(String param) {
        String sql = null;
        for (int i = 0; i < sqls.length; i++) {
            if (param.equals(PARAMS[i])) {
                sql = sqls[i];
            }
        }
        return sql;
    }

    public void init() throws ServletException {
        this.log("init() run");
        ServletContext context = this.getServletContext();

        url = context.getInitParameter("url");
        username = context.getInitParameter("username");
        password = context.getInitParameter("password");
        driverClassName = context.getInitParameter("driverClassName");
        for (int i = 0; i < PARAMS.length; i++) {
            sqls[i] = context.getInitParameter(PARAMS[i]);
        }
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        this.log("doGet() run");
        response.setContentType("text/html; charset=Shift_JIS");
        PrintWriter writer = response.getWriter();
        writer.println("<html><head><title>"
                + "Servlet3章Exercise2</title></head><body>");
        if (!this.isEmptySqls()) {
            StringBuffer buffer = new StringBuffer();

            buffer.append("<form action=\"\" method=\"post\">");
            for (int i = 0; i < PARAMS.length; i++) {
                buffer.append("<input type=\"radio\" name=\"sql\" value=\"");
                buffer.append(PARAMS[i]).append("\">");
                buffer.append(PARAMS[i].toUpperCase()).append("<br>");
            }
            buffer.append("<input type=\"submit\" value=\"送信\">");
            buffer.append("</form>");
            writer.println(buffer.toString());
        }
        writer.println("</body></html>");

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        this.log("doPost() run");
        response.setContentType("text/html; charset=Shift_JIS");
        PrintWriter writer = response.getWriter();
        writer.println("<html><head><title>"
                + "Servlet3章Exercise2</title></head><body>");
        String param = request.getParameter("sql");
        if (param != null) {
            String sql = getSuitableSql(param);
            Connection conn = null;
            try {
                conn = this.getConnection();
                writer.println(getHtmlTable(request, response, conn, sql));
            } catch (SQLException e) {
                this.log("doPost()", e);
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        } else {
            writer.println("SQL文を選択してください。<br>");
        }
        writer.println("<a href=\"servlet3-2\">戻る</a></body></html>");
    }

}

↑このページの先頭へ

こちらもチェック!

PR
  • XMLDB.jp