JSPはこれには間違った場所です。JDBCジョブを実行するスタンドアロンクラスを作成し、SQLが失敗するたびに、各メソッドが例外をスローするようにする必要があります。
User
これは、テーブル上のすべてのJDBC処理を実行する「DAO」クラスの例です。
public class UserDAO {
public User find(String username, String password) throws SQLException {
// ...
}
public void save(User user) throws SQLException {
// ...
}
public void delete(User user) throws SQLException {
// ...
}
}
次に、このクラスを使用して例外を処理するサーブレットを作成します。LoginServlet
これが:の例です。
@WebServlet(urlPatterns={"/login"})
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDAO = new UserDAO();
try {
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login.
response.sendRedirect("userhome");
} else {
request.setAttribute("message", "Unknown login, try again"); // Set error message.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Redisplay form with error.
}
} catch (SQLException e) {
throw new ServletException("Fatal database failure", e); // <-- Here
}
}
}
JSPをこのサーブレットに送信させます
<form action="login" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
${message}
</form>
ご覧のとおり、DAOクラスがをスローするSQLException
と、サーブレットはそれを。として再スローしますServletException
。デフォルトでは、コンテナデフォルトのHTTP500エラーページに表示されます。必要に応じて、次のように独自のルックアンドフィールでJSPを使用してこれをカスタマイズできます。
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
参照: