【发布时间】:2021-08-03 04:19:07
【问题描述】:
我是一个初学者,这是一个学校作业,但我的问题不是关于作业的功能方面。
我必须使用 Java bean 和 JSP 来执行各种数据库功能,例如创建表、更新表、删除表等。我的所有页面都正常工作,但是我想在一个方法时向页面输出一条消息是否运行,取决于操作是否成功。
现在我有错误/成功消息通过System.out.println() 发送到控制台,它工作正常,但我希望它显示在页面上,以便用户查看操作是否成功。我一直在网上寻找,似乎我需要使用 PrintWriter out = response.getWriter();这样我就可以使用out.println(); 将我的成功/错误消息发送到 JSP 而不是控制台。
我导入了 java.io.PrintWriter,当我添加 PrintWriter out = response.getWriter();对于我的一种方法,我得到“无法解决响应。”
在网上看到有人说要创建一个参数'response',这是Eclipse中的聪明建议之一。当我这样做时,它会将(ServletResponse 响应)作为参数添加到我的方法中,并且我必须包含一个“抛出 IOException”声明。那么问题是我的 JSP 不会运行该方法,因为我没有向它传递参数。
所以我尝试的下一件事是在方法中声明响应变量(另一个 Eclipse 建议)。我单击建议的修复程序,它会添加 ServletResponse 响应;
现在我得到变量需要初始化的错误,这是有道理的。但是当我让 Eclipse 为我初始化它时,它会设置 response = null;
此时它清除了错误,但是当我尝试运行它时,我得到:
java.lang.NullPointerException:无法调用 "javax.servlet.ServletResponse.getWriter()"
因为“响应”为空
我不确定我是否缺少一些简单的东西,或者我只是误解了使用 PrintWriter 的整个概念。我已经看到了几篇解决这个问题的帖子,但它们都不适用于我正在尝试做的事情。
我将只包括 DROP TABLE 方法和 JSP,因为它是最简单的方法。
这是我的 Bean 代码:
// This drop table method can be used to clear the tables
public void dropTable() {
Connection con = null;
Statement stmt = null;
// Attempt to connect to the database
try{
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "student1","pass");
stmt = con.createStatement();
}
// Catch any exceptions and display a failure message before exiting the program
catch(Exception e){
System.out.println(e);
System.exit(0);
}
// Attempt to DROP the tables if they exist
try {
stmt.executeUpdate("DROP TABLE CUSTOMERS");
stmt.executeUpdate("DROP TABLE ITEMS");
System.out.println("Tables Dropped");
//Close the statement and connection
stmt.close();
con.close();
}
// Catch any exceptions
catch (SQLException e) {
System.out.println(e);
}
}
这是我非常简单的 JSP,带有一个按钮,当按下该按钮时,将调用指向同一 JSP 并从我的 Bean 运行 dropTable() 方法的 POST 方法。
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!-- Create the main HTML for the page -->
<!DOCTYPE html>
<html>
<head>
<title>Drop Tables</title>
</head>
<body>
<div>
<h1>Click the button to drop the CUSTOMERS and ITEMS tables</h1>
<form method="post">
<input type='submit' value='Drop'/>
</form>
<br>
<!-- Invoke and name the JavaBean to be used -->
<jsp:useBean id='DBBean' class='bubsBeans.DBBean' />
<!-- Java code to determine if the post method has been invoked through the submit button click -->
<%
// If the POST method is invoked invoke the dropTable method from the bean
if(request.getMethod().equals("POST")){
DBBean.dropTable();
}
%>
</div>
</body>
</html>
【问题讨论】:
-
我只能说你这个问题问得很好。您准确地发布了您遇到的问题以及所有相关代码。干得好!
-
谢谢!我试图提供尽可能多的信息和背景,因为那里有很多类似但不完全是我要问的问题。我知道当我尝试解决问题时,尽可能多地获取信息会有所帮助。