473,748 Members | 4,030 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Java Servlet Problem. Help anyone?

16 New Member
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 2618
r035198x
13,262 MVP
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 New Member
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
2773
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 via its doGet() method and does no action. Has anyone here successfully ever sent anything via PHP to a Java servlet? Tell me what you are supposed to do, I thought it was this simple:
1
3476
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 of PHP 4. (release and dev) I would appreciate any help with this issue. -- Chris
2
3958
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 create. If I destroy other objects that I don't need any more, then I can create more "cell" objects. Unfortunately, I cannot destroy any more of my other objects without breaking the program. This does not appear to be a problem that is...
3
4802
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 servlet-classes I needed on the java.sun.com-Homepage and downloaded the javax.servlet-Package. (Maybe this file-description may help you understanding my problem:
3
7221
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 functionality in Java provided by some controls (ActiveX) and I was wondering if I can manipulate them using Java? Thanks in advance, Carl
1
6918
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
3493
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 am having a serious problem with the latest connector. During login, it seems to me that when validating the password, which is stored as a byte array in the database, the MySql connector is passing back the password info as a Byte. The...
0
2605
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 with a XML file. I want to be able to save the form automatically for the User so as to prevent typing errors i.e. c:/erikaTemp/subFolder/erika_12345.pdf but from what I've seen this can only be done via the the 'File download' pop up which only...
7
9593
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 image. But i executed that command in jsp Program .It didn't work.It shows error.
0
8831
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9548
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9374
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4876
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.