By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,904 Members | 925 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,904 IT Pros & Developers. It's quick & easy.

Java Servlet Problem. Help anyone?

P: 16
Hey! I've got a little problem. I have to make a web site for a university essay. I curently have to create a search engine. Users can enter a hotel name in a search bar and results have to appear in another screen. All of this has to be done with java servlets. I think there's something I don't see and it's wrong. My problem is that anything I enter in the search bar appears as a result in the results page, even if there's not such a name in the database. So if i enter eg "asdfa" it will show asdfa in the results page. Here's the code I've made so far. I think that the java file that connects to the database is right. I checked the query in MySQL and it's right. The search form is also right, using the post method and forwarding input to the Search Receiver servlet. The SearchReceiver file might be the wrong one... Any suggestions, help, heads up? :)

SearchReceiver
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import javax.servlet.*;
  3. import javax.servlet.http.*;
  4. import java.sql.*;
  5. /**
  6.  * @author ismgroup
  7.  */
  8. public class SearchReceiver extends HttpServlet {
  9.  
  10.   /**
  11.    * Handles HTTP POST requests.
  12.    *
  13.    * @param request
  14.    *            the request object
  15.    * @param response
  16.    *            the response object
  17.    *
  18.    * @throws IOException
  19.    *             if an input or output error is detected when the servlet
  20.    *             handles the GET request
  21.    * @throws ServletException
  22.    *             if the request for the GET could not be handled
  23.    */
  24.   public void doPost(HttpServletRequest request, HttpServletResponse response)
  25.       throws IOException, ServletException {
  26.  
  27.     response.setContentType("text/html; charset=ISO-8859-7");
  28.     PrintWriter out = new PrintWriter(response.getWriter(), true);
  29.  
  30.     /*
  31.      * gets parameters from the request.
  32.      */
  33.     String searchInput = request.getParameter("nameField");
  34.  
  35.     /*
  36.      * Converts from ISO-8859-1 to ISO-8859-7 (Greek) in case
  37.      * the user typed his/her name in Greek
  38.      */
  39.  
  40.  
  41.     try {
  42.       /*
  43.        * checks if all the parameters have value.
  44.        */
  45.  
  46.  
  47.         dbConnector theConnector2 = new dbConnector(searchInput);
  48.         theConnector2.open();
  49.  
  50.         if(!(searchInput.length()>0)) {
  51.             theConnector2.close();
  52.             RequestDispatcher dispatcher1 = getServletContext().getRequestDispatcher("/servlet/searchError");
  53.             dispatcher1.forward(request, response);
  54.  
  55.         }
  56.  
  57.  
  58.             theConnector2.searchProcess();
  59.             theConnector2.close();
  60.  
  61.             out.println("<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>");
  62.               out.println("<html>");
  63.               out.println("<head>");
  64.               out.println("  <meta content='text/html; charset=windows-1253'");
  65.               out.println(" http-equiv='content-type'>");
  66.               out.println("  <title>Search Results</title>");
  67.               out.println("</head>");
  68.               out.println("<body style='color: rgb(0, 0, 0); background-color: rgb(51, 255, 51);'");
  69.               out.println(" alink='#000099' link='#000099' vlink='#990099'>");
  70.               out.println("<div style='text-align: center;'>");
  71.               out.println("<h1>Search Results</h1>");
  72.               out.println("<br>");
  73.               out.println(searchInput + "<br>");
  74.               out.println("<span style='font-weight: bold;'><br>");
  75.               out.println("<br>");
  76.               out.println("<br>");
  77.               out.println("<br>");
  78.               out.println("<br>");
  79.               out.println("<br>");
  80.               out.println("<br>");
  81.              out.println("<br>");
  82.               out.println("<br>");
  83.               out.println("<br>");
  84.               out.println("<br>");
  85.               out.println("<br>");
  86.               out.println("<br>");
  87.               out.println("<br>");
  88.               out.println("<br>");
  89.               out.println("</span>");
  90.               out.println("<hr style='width: 100%; height: 2px;'>");
  91.               out.println("<div style='text-align: left;'><span style='font-weight: bold;'></span>Back to");
  92.               out.println("στην <a href='../optimusHotels.html'>main page...</a><br>");
  93.               out.println("<span style='font-weight: bold;'></span></div>");
  94.               out.println("<br>");
  95.               out.println("</div>");
  96.               out.println("</body>");
  97.               out.println("</html>");
  98.               theConnector2.close();
  99.  
  100.  
  101.     } catch (Exception ex) {
  102.       out.println("<html>");
  103.       out.println("<body");
  104.       out.println("Exception: " + ex.getMessage());
  105.       out.println("</body>");
  106.       out.println("</html>");
  107.     }
  108.   }
  109. }
Database Connector
Expand|Select|Wrap|Line Numbers
  1. import java.sql.*;
  2. import java.io.*;
  3. import javax.servlet.*;
  4. import javax.servlet.http.*;
  5.  
  6. /**
  7.  * Provides all necessary methods in order to carry out a transaction with
  8.  * database.
  9.  *
  10.  * @author Nikos 
  11.  */
  12. class dbConnector {
  13.  
  14.  
  15.  
  16.   private String searchInput = "";
  17.  
  18.   private String errorMessages = "";
  19.  
  20.   private Connection con = null;
  21.  
  22.   private PreparedStatement stmt = null;
  23.  
  24.  
  25.   private ResultSet rs = null
  26.  
  27.  
  28.   private final String searchQuery = "select hotelName from hotel where hotelName like '%?%'";
  29.   /**
  30.    * A method to get errors.
  31.    *
  32.    * @return String, representing the error message.
  33.    */
  34.   public String getErrorMessages() {
  35.     return errorMessages;
  36.   }
  37.  
  38.   /**
  39.    * The Constructor.
  40.    *
  41.      */
  42.  
  43.   public dbConnector(String searchInput) {
  44.         this.searchInput = searchInput;
  45.   }
  46.  
  47.   /**
  48.    * Provides a connection with the Database Server. Initializes JDBC driver
  49.    * for MySQL. Establishes a connection with the Database Server.
  50.    *
  51.    * @throws SQLException
  52.    *             (with the appropriate message) if any driver or connection
  53.    *             error occured.
  54.    */
  55.   public void open() throws SQLException {
  56.     try {
  57.       // for JDBC driver to connect to mysql, the .newInstance() method
  58.       // can be ommited
  59.       Class.forName("com.mysql.jdbc.Driver").newInstance();
  60.     } catch (Exception e1) {
  61.       errorMessages = "MySQL Driver error: <br>" + e1.getMessage();
  62.       throw new SQLException(errorMessages);
  63.     }
  64.  
  65.     try {
  66.       con = DriverManager.getConnection(
  67.           "jdbc:mysql://*"******",
  68.           "******", "******");
  69.     } catch (Exception e2) {
  70.       errorMessages = "Could not establish connection with the Database Server: <br>"
  71.           + e2.getMessage();
  72.       con = null;
  73.       throw new SQLException(errorMessages);
  74.     }
  75.  
  76.   }
  77.  
  78.   /**
  79.    * Ends the connection with the database Server. Closes all Statements and
  80.    * ResultSets. Finally, closes the connection with the Database Server.
  81.    *
  82.    * @throws SQLException
  83.    *             (with the appropriate message) if any error occured.
  84.    */
  85.   public void close() throws SQLException {
  86.     try {
  87.  
  88.       if (stmt != null)
  89.         stmt.close();
  90.  
  91.  
  92.       if (rs != null)
  93.         rs.close();
  94.  
  95.       if (con != null)
  96.         con.close();
  97.  
  98.     } catch (Exception e3) {
  99.       errorMessages = "Could not close connection with the Database Server: <br>"
  100.           + e3.getMessage();
  101.       throw new SQLException(errorMessages);
  102.     }
  103.   }
  104.  
  105.   public boolean searchProcess() {
  106.  
  107.       if (con == null) {
  108.         errorMessages = "You must establish a connection first!";
  109.         return false;
  110.       }
  111.  
  112.       try {
  113.           stmt = con.prepareStatement(searchQuery);
  114.         stmt.setString(1, searchInput);
  115.         // execute query
  116.         rs = stmt.executeQuery();
  117.  
  118.         int counter = 0;
  119.  
  120.         while (rs.next())
  121.           counter++;
  122.  
  123.         if (counter == 1) {
  124.           stmt.close();
  125.           rs.close();
  126.           return true;
  127.         } else {
  128.           errorMessages = "Error Login: <br>Invalide username or password!";
  129.           stmt.close();
  130.           rs.close();
  131.           return false;
  132.         }
  133.       } catch (Exception e4) {
  134.         errorMessages = "Error while executing authentication query: <br>"
  135.             + e4.getMessage();
  136.         return false;
  137.       }
  138.   }
  139.  
  140. }// end of class
Jan 7 '08 #1
Share this Question
Share on Google+
2 Replies


10K+
P: 13,264
That's because line 73 of your SearchReceiver servlet is simply printing the value that was entered for the search. It should print out values from the database instead.

P.S I'd rather not generate static html from a servlet like that. Have a separate display JSP and pass it parameters from the servlet which it then displays.
Jan 7 '08 #2

P: 16
That's because line 73 of your SearchReceiver servlet is simply printing the value that was entered for the search. It should print out values from the database instead.

P.S I'd rather not generate static html from a servlet like that. Have a separate display JSP and pass it parameters from the servlet which it then displays.

How am I gonna make it print values from the database using the searchProcess method of Dbconnector file?
I'm stuck.

So you say that It's better to make a seperate java servlet file that will take the SearchReceiver input and use the method etc? Am I right?
Jan 7 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.