Reputation: 69
I'm a beginner and this is for a school assignment, but my question is not about the functional aspects of the assignment.
I have to use java beans and JSPs to perform various database functions like Create tables, update tables, drop tables, etc. I have all of my pages working properly, but I want to output a message to the page when a method is run, depending on if the operation was successful or not.
Right now I have the error/success messages going to the console with System.out.println()
, and it's working fine, but I want it to display on the page so that a user will see if the operation was successful or not. I've been looking online and it seems like I need to use PrintWriter out = response.getWriter(); so that I can use out.println();
to send my success/error messages to the JSP instead of the console.
I imported java.io.PrintWriter and when I add PrintWriter out = response.getWriter(); to one of my methods, I get "response cannot be resolved."
Looking online I saw someone say to create a parameter 'response', which is one of the smart suggestions in Eclipse. When I do that it adds (ServletResponse response) as a parameter to my method and I have to include a "throws IOException" declaration. The problem then is that my JSP won't run the method because I'm not passing an argument to it.
So the next thing I tried was declaring the response variable in the method (another Eclipse suggestion). I click the suggested fix and it adds ServletResponse response;
Now I get the error that the variable needs to be initialized, which makes sense. But when I let Eclipse initialize it for me it sets response = null;
At this point it clears the errors, but when I try to run it I get:
java.lang.NullPointerException: Cannot invoke "javax.servlet.ServletResponse.getWriter()"
because "response" is null
I'm not sure if it's something simple that I'm missing or I'm just misunderstanding the whole concept of using PrintWriter. I've seen several posts addressing this, but none of them work for what I'm trying to do.
I'll only include the DROP TABLE method and JSP because it's the simplest method.
Here's my Bean code:
// 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);
}
}
Here is my very simple JSP with a button that when pressed invokes the POST method that points back at the same JSP and runs the dropTable()
method from my Bean.
<%@ 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>
Upvotes: 1
Views: 757
Reputation: 69
Based on Yserbius' response, I understand where I was going wrong with the getWriter. Here's my solution in case anyone else comes across this and needs the help.
I initialized a new String variable in the method and assigned my messages to that variable. Then I changed my method to return that string instead of void.
That way in my JSP I can assign the returned value of the method as a string and it will perform the database function (or throw an exception) and return the proper message to my JSP String variable.
Then I can use out.print(messageVariable);
to print the message to the page.
Like most things I agonize over in Java, it was a simple solution that I was looking past repeatedly.
Here's my new method code:
// This drop table method can be used to clear the table
public String dropTable() {
Connection con = null;
Statement stmt = null;
String message;
// 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){
message = "Error connecting to database.";
System.exit(0);
}
// Attempt to DROP the table if it exists
try {
stmt.executeUpdate("DROP TABLE CUSTOMERS");
stmt.executeUpdate("DROP TABLE ITEMS");
message = "Tables Dropped.";
//Close the statement and connection
stmt.close();
con.close();
}
// Catch any exceptions
catch (SQLException e) {
message = e.toString();
}
return message;
}
Here's the pertinent part of my new JSP code:
<%
// If the POST method is invoked, invoke the dropTable method from the bean
if(request.getMethod().equals("POST")){
String message = DBBean.dropTable();
out.print(message);
}
%>
Upvotes: 1
Reputation: 1414
The response
object is implicitly declared in your JSP. So you can use something like this code <% response.getWriter().println("Debugging Code"); %>
anywhere in your JSP. But the servlet is just a regular Java class and everything needs to be declared explicitly. If you want to use response
, it's passed as a parameter to your doPost
or doGet
method as an HttpServletResponse
.
Upvotes: 1