473,385 Members | 1,772 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Java Servlet Problem. Help anyone?

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
2 2588
r035198x
13,262 8TB
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
dmstn
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

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

Similar topics

3
by: Phil Powell | last post by:
I have a PHP script that will be doing an @fopen file open command to a Java servlet, sending content via a query string. Problem is that it appears the Java servlet does not receive anything...
1
by: Chris Morgan | last post by:
I'm trying to get php to run on my webserver as a Java Servlet, it works the first time but fails the second time and crashes the JVM with the following error: I have tried the latest versions...
2
by: Patrick | last post by:
I'm using Jakarta-POI to create a huge Excel spreadsheet. I get the error below when the spreadsheet grows to a large size. It seems to have something to do with the number of "cell" objects that I...
3
by: TheLetti | last post by:
Hy! I've just downloaded the latest Java 2 SDK (j2sdk1.4.2_01). For my surprise in this version the servlet-classes are not integrated (e.g. the class javax.servlet). So I found all the...
3
by: S C A | last post by:
Dear All: I'm not sure if this is even possible but does anyone know about using ActiveX controls (a Microsoft-specific technology) in Java? I am having a heck of a time finding some similar...
1
by: ptaz | last post by:
Hi I'm trying to run a web page but I get the following error. Ca anyone please tell me a solution to this. Thanks Ptaz HTTP Status 500 - type Exception report
2
by: Dan | last post by:
Hello. I have recently tried upgrading the MySql connector for my servlet from 2.0.4 to 3.0.9. I have found a minor limitation in 2.0.4 and was hoping that 3.0.9 would fix it. However, now I...
0
by: ErikaW | last post by:
Hi all, I've tried to google this but could not find a clear solution. I have a Web application developed in JDevloper using mostly html and Javascript. I have a pre-defined PDF form which I merge...
7
by: swethak | last post by:
Hi, i have a command to convert the video file into image ffmpeg -i sample.wmv -f image2 -t 0.001 -ss 3 ss.jpg i run that one in command prompt it converted the video file into...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.