1

I cannot get my out string to print to my .jsp file after the post method is run. Below are my .java and .jsp files. I have removed the code there as by this time I know what I was trying was far from intuitive. I have simply left comments where I know the two respective lines of code need to go. I am simply trying to print the string "out" in my .jsp file after the servlet has executed the SQL command.

EDIT: I finally have all of my output going to the JSP page. The only problem I'm having now is that my less-than-ideal method of storing my query results in the out string is leading to my output being one long line of results, instead of a nice spacing or table. I know I would be better off looping through the results in a table in the jsp, but I can't seem to get that to work either.

dbServlet.jsp

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
    <title>MySQL Servlet</title>
    <style type="text/css">
        body{background-color: green;}
    </style>
</head>
<body>
    <h1>Hello World!</h1>
    <h2>This is the MySQL Servlet</h2>
    <form action = "/database/database" method = "post">
    <p>
        <label>Enter your query and click the button to invoke a MySQL Servlet
            <input type = "text" name = "query" />
            <input type = "submit" value = "Run MySQL Servlet" />
        </label>
    </p>
    </form>
    <hr>
    <%= request.getAttribute("queryResults") %>
</body>
</html>

databaseServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

@SuppressWarnings("serial")

public class databaseServlet extends HttpServlet {
    private Connection conn;
    private Statement statement;

    public void init(ServletConfig config) throws ServletException {
        try {
            Class.forName(config.getInitParameter("databaseDriver"));
            conn = DriverManager.getConnection(
                    config.getInitParameter("databaseName"),
                    config.getInitParameter("username"),
                    config.getInitParameter("password"));
            statement = conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String out = "\n";

        String query = request.getParameter("query");

        if (query.toString().toLowerCase().contains("select")) {
            //SELECT Queries
            try {
                ResultSet resultSet = statement.executeQuery(query.toString());
                ResultSetMetaData metaData = resultSet.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
                for(int i = 1; i<= numberOfColumns; i++){
                    out = out + "\t" + metaData.getColumnName(i) + "\n";
                }
                out = out + "\n";

                while (resultSet.next()){
                    for (int i = 1; i <= numberOfColumns; i++){
                        out = out + "\t" + resultSet.getObject(i) + "\n";
                    }
                    out = out + "\n";
                 }
            }
            catch (Exception f) {
                f.printStackTrace();
            }
        }
        else if (query.toString().toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
            //DELETE and INSERT commands
            try {
                conn.prepareStatement(query.toString()).executeUpdate(query.toString());
                out = "\t\t Database has been updated!";
            }
            catch (Exception l){
                l.printStackTrace();
            }
        }
        else {
            //Not a valid response
            out = "\t\t Not a valid command or query!";
        }
        request.setAttribute("queryResults", out);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
        dispatcher.forward(request,  response);
    }
}
PeerPressure
  • 251
  • 3
  • 7
  • 15
  • It would be good to read [How to use Servlets and Ajax?](http://stackoverflow.com/q/4112686/1065197). Note that BalusC shows how to call the Servlet using GET, but you can do similar for POST with few changes. – Luiggi Mendoza Nov 15 '12 at 23:41
  • I can't decide whether to use a java bean or what... What about using response.setAttribute()? Could I set an attribute that could be read from the .jsp file? All I'm trying to do is pass a single string. – PeerPressure Nov 15 '12 at 23:54
  • 1
    It looks like you don't understand the basics of web application. The Servlet will receive a request from the client (the user browser), process it and can prepare the response from the server to the client (that's why you have both as parameters). In case of normal request-response, the client will print the response content (in your case, it looks like it will print a blank page). The technology evolved and [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) request/responses are available. – Luiggi Mendoza Nov 16 '12 at 00:01
  • More info: [Where to start from in web development?](http://stackoverflow.com/q/543091/1065197), [Java web development, what skills do I need?](http://stackoverflow.com/q/1958808/1065197). – Luiggi Mendoza Nov 16 '12 at 00:04
  • I've updated my code to where I'm at now. I can't believe how close it is, and that I just can't get it to output on the .jsp instead of its own page. I've been through your examples, this really isn't that deep. – PeerPressure Nov 16 '12 at 02:14

1 Answers1

0

You cannot just do an out.println and print on the JSP. YOu need to put it into your response object and forward to the JSP. The JSP can then pick it up and print.

Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66
  • You say that, but I have tried that, and like I said, I then cannot even execute my .jsp page. I don't know if it is syntax or what. Numerous examples say to do just what I've done: http://www.coderanch.com/t/571948/JSP/java/print-values-jsp-page-fetched Is my problem that I'm using a printwriter? Should I just be declaring out as a string, and appending to it? – PeerPressure Nov 16 '12 at 02:27
  • you should just add the string in `request.setAttribute("queryResults", out);` instead of 'out' – Vaishak Suresh Nov 16 '12 at 02:31
  • i updated the most recent version so you can see what i'm trying to do. it just wont output my data anymore. should out not be a string? – PeerPressure Nov 16 '12 at 03:23
  • 1
    Set the attribute and then forward. `dispatcher.forward(request, response); request.setAttribute("queryResults", out);` Reverse the above 2 lines. – Vaishak Suresh Nov 16 '12 at 03:45
  • made the change in my code and in the question, still nada :-/ – PeerPressure Nov 16 '12 at 04:18
  • Okay! I am getting out to print to the .jsp file when it is an invalid query. That means it is working on that end. Now the only problem I am having is that the query results for SELECT statements are not being properly set to out. I think using concat might be the wrong approach? What do you think? – PeerPressure Nov 16 '12 at 04:21
  • @Animachine Did you debug and check if the code is actually executing for valid queries? Personally, I would not use concat. That is not what concat is meant for. Look at using StringBuffer or StringBuilder and do a stringBufferObject.toString() when you finally write it to the response. – Vaishak Suresh Nov 16 '12 at 04:34
  • I updated my .java file in my question once again. I have abandoned concat, and now I have all of the output being printed, so yippee! But it just all prints in one line. Even adding \n and \t characters to the string won't change it. – PeerPressure Nov 16 '12 at 04:39
  • Consider using StringBuffer instead of String. Strings are immutable and not optimal if you append multiple times. Happy Coding! PS: Care to mark the question answered? – Vaishak Suresh Nov 16 '12 at 04:41