1

I am writing simple servlet program in which home page is displayed. There i have given account no, and have to click on submit. this have to call my servlet and show balance. I have written this in eclipse. Folder structure of project is as below I have account.html inside webcontent folder and web.xml inside web-inf.

when i click on submit i am getting 404 saying/WelcomeServlet not found. please help me..

 **account.html**
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bank Account</title>
</head>
<body bgcolor="Gold">
<center><h1>Account  Enquiry</h1>
<form action="/WelcomeServlet">
Account Number : <input type = "text" Name = "t1"><br><br>
<input type="submit" value="GetBalance">
</form></center>
</body>
</html>

here is web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>app1</display-name>
  <welcome-file-list>
    <welcome-file>account.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <display-name>WelcomeServlet</display-name>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>com.stc.WelcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/WelcomeServlet</url-pattern>
  </servlet-mapping>
</web-app>
--------------

Here is WelcomeServlet:

package com.stc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class WelcomeServlet
 */
public class WelcomeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Connection conn ;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public WelcomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init(ServletConfig sc){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/test");

        }
        catch (Exception e) {
            // TODO: handle exception
        }
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<body bgcolor = grey>");
        try {
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("select balance from Account where accno = " +request.getParameter("t1"));
            if(rs.next()) {
                out.println("<h1>Balance is SAR:" +rs.getFloat(3)+"</h1>");
            }else {
                out.println("<h1>Account details does not exist</h1>");
            }
            rs.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.println("</body></HTML>");
        out.close();
    }



}
Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38

1 Answers1

1

The following servlet worked for me (Tomcat 7.0.40, java version "1.6.0_45"). Note that:

  1. The leading '/' was required in web.xml for the <url-pattern>--I tested it. And my Head First Servlets book says the leading slash is required(2004, p.586). The leading slash also seems to be required for the new syntax: @WebServlet("/WelcomeServlet"). Without the leading slash, my project threw all kinds of exceptions.

  2. A leading slash is not required in the form's action attribute. The browser has rules for assembling urls from relative paths(i.e. ones that don't start with a slash), to produce the final url. So for the form's action attribute, you can use either an absolute path(leading slash) or a relative path(no leading slash) as long as the relative path resolves to the same path as the correct absolute path. The correct absolute path starts with the project's name.

  3. I had to specify the username and password in getConnection(), which for me are 'root' and ''. There is a version of getConnection() that doesn't take a username and password, but I don't know how that would work.

  4. For getFloat(), the column number had to be exactly 1; neither 2 nor 0 would work, which made sense after reading the docs:

float getFloat(int columnIndex) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a float in the Java programming language. Parameters: columnIndex - the first column is 1, the second is 2, ...
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getFloat(int)

Your select only retrieves one thing from a customer's record: the balance. As a result, your row only has one column.

package com.stc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class WelcomeServlet
 */
public class WelcomeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Connection conn ;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public WelcomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init(ServletConfig sc){
        try {
            //ADDED this line:
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/my_db",
                    "root",
                    ""
            );

        }
        catch (Exception e) {
            System.out.println("Couldn't create connection.");
            // TODO: handle exception
        }
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                                    throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<body bgcolor = grey>");
        try {
            Statement st = conn.createStatement();
            String accno = request.getParameter("t1");
            ResultSet rs = st.executeQuery("SELECT balance FROM accounts WHERE accno = " +request.getParameter("t1"));
            if(rs.next()) {
                out.println("<h1>Balance is SAR:" +rs.getFloat(1)+"</h1>");
            }else {
                out.println("<h1>Account details does not exist</h1>");
            }
            rs.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.println("</body></HTML>");
        out.close();
    }



}
7stud
  • 46,922
  • 14
  • 101
  • 127
  • Hi,Thanks for the reply. i tried with that but still not working – user2470190 Jun 10 '13 at 10:07
  • @user2470190, I made some changes to your servlet, and then it operated as expected. – 7stud Jun 11 '13 at 02:38
  • I think no changes required in servlet.Problem here servlet is not starting execution.it didnt find the resource WelcomeServlet.Still i am unable to get..How you run this.. – user2470190 Jun 11 '13 at 09:08
  • I was getting the same error you did when I ran your program as is. Check the logs. I compiled your servlet by hand and moved it by hand into Tomcat's directory structure. Also, I had to restart Tomcat every time I made a change to the servlet. – 7stud Jun 11 '13 at 09:11
  • Why is it that you think rs.getFloat(3) is not an error after reading my post? – 7stud Jun 11 '13 at 10:10
  • Yes, rs.getFloat(3), is an error. As i have given query as select balance. If i have given select * it is rs.getFloat(3).OK, but instead of changing also, i am unable to run the servlet from html. If i run the servlet individually, its running but not in application. – user2470190 Jun 12 '13 at 07:14
  • Next, how do you expect to connect to mysql without providing a username and password? – 7stud Jun 12 '13 at 07:17
  • No problem, anyway, i have given username and pswd in my code. – user2470190 Jun 12 '13 at 07:21
  • so, still i didnt get where i commited mistake in calling the servlet.Mistake is not with calling. my html is calling WelcomeServlet but unable to find the servlet in the path...please help – user2470190 Jun 12 '13 at 07:27
  • Have you ever once checked the server logs? – 7stud Jun 12 '13 at 07:57
  • Have you ever written a plain java program that successfully connected to a mysql database and retrieved information? – 7stud Jun 12 '13 at 08:03
  • Have you ever written a servlet that worked in eclipse before? If not, you may want to try a simpler servlet. – 7stud Jun 12 '13 at 08:05
  • Have you ever written a servlet without eclipse? If not, why not? – 7stud Jun 12 '13 at 08:05
  • I don't know how eclipse works, but I have to restart my server every time I make a change to my servlet, and of course I have to recompile my servlet every time I make a change. – 7stud Jun 12 '13 at 08:09
  • I've been trying to get your servlet to work in eclipse. I got the same error you got, over and over again. Then I read that the path in your form has to have the project name in it--and you should always specify the _method_ attribute as well, so:
    . Now eclipse finds and executes the servlet, but I get an error connecting to the database. I configured eclipse for mysql, and then I had eclipse perform a test ping to the database, and that was successful, but the servlet still can't connect. Let me know if you get that to work.
    – 7stud Jun 12 '13 at 16:29
  • My God. I got _my_ version of your servlet to work in eclipse. I guess you have to move a copy of the mysql connector jar file into Tomcat/lib. – 7stud Jun 12 '13 at 16:44
  • Also, if a path in a form's action attribute does not have a leading slash, the browser will take the current page's url, e.g. `http://localhost:8181/com.stc/account.htm` and substitute the specified path in place of the last name. So if the form's action attribute is: `action="WelcomeServlet"`, the url for the request becomes: `http://localhost:8181/com.stc/WelcomeServlet`. – 7stud Jun 12 '13 at 17:03
  • By the way, sometimes when I changed the file account.html, e.g. adjusting the paths in the action attribute, Tomcat did not recognize the changes and eclipse did not ask me if I wanted to restart Tomcat, so I had to manually restart Tomcat. – 7stud Jun 12 '13 at 17:18
  • Another day, new problems. When I tried to run the WelcomeServlet in eclipse today, Tomcat would not start up, I got all kinds of errors. To solve those errors, I right clicked on the server name and then I selected `Clean...`. Yesterday, I had been running the project by right clicking on account.html and selecting `Run as/Run on Server` but today that produced a null pointer exception in the WelcomeServlet code when the code tried to establish a database connection... – 7stud Jun 13 '13 at 05:22
  • ...To solve that problem, I right clicked on the project name and selected `Run as/Run on Server`. That entered the url: `http://localhost:12566//` in the browser, which produced a 404 error because there is no index.html page in my proj. But tacking on `account.html` to the url and refreshing the browser caused the account.html to be displayed, and then the WelcomeServlet worked. – 7stud Jun 13 '13 at 05:22
  • Thanks a lot 7stud, you have done a great job. I changed the path as you said and tried, i also recive null pointer for conn obj, then as you said i copied my-sql-connector.jar in tomcat\lib. then worked successfully – user2470190 Jun 15 '13 at 07:50