1

我正在编写显示主页的简单 servlet 程序。那里我给了账号,必须点击提交。这必须调用我的 servlet 并显示平衡。我已经在eclipse中写了这个。项目的文件夹结构如下我在webcontent文件夹中有account.html,在web-inf中有web.xml。

当我点击提交时,我得到 404 说/WelcomeServlet not found。请帮我..

 **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>

这是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>
--------------

这是 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();
    }



}
4

1 回答 1

1

以下 servlet 对我有用(Tomcat 7.0.40,java 版本“1.6.0_45”)。注意:

  1. web.xml 中需要前导“/”用于--我对其进行了<url-pattern>测试。我的 Head First Servlets 书说需要前导斜杠(2004,p.586)。新语法似乎也需要前导斜杠:@WebServlet("/WelcomeServlet"). 如果没有前导斜线,我的项目会抛出各种异常。

  2. 表单的 action 属性中不需要前导斜杠。浏览器具有从相对路径(即不以斜杠开头的路径)组装 url 的规则,以生成最终 url。因此,对于表单的 action 属性,您可以使用绝对路径(前导斜杠)或相对路径(无前导斜杠),只要相对路径解析为与正确绝对路径相同的路径即可。正确的绝对路径以项目名称开头。

  3. 我必须在 getConnection() 中指定用户名和密码,对我来说是 'root' 和 ''。有一个版本的 getConnection() 不需要用户名和密码,但我不知道它是如何工作的。

  4. 对于 getFloat(),列号必须正好为 1;2 和 0 都不起作用,这在阅读文档后是有意义的:

float getFloat(int columnIndex) throws SQLException 检索此 ResultSet 对象的当前行中指定列的值,作为 Java 编程语言中的浮点数。参数: columnIndex - 第一列为 1,第二列为 2,...
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getFloat(int)

您的选择仅从客户记录中检索一件事:余额。结果,您的行只有一列。

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();
    }



}
于 2013-06-10T09:36:41.943 回答