为什么程序显示404错误..单击时显示HTML页面

时间:2012-03-28 13:10:38

标签: servlets sample

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 
  xmlns="http://java.sun.com/xml/ns/j2ee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
                      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>FirstProject</display-name>

    <servlet>
    <servlet-name>ServletClass1</servlet-name>
    <servlet-class>com.test.ServletClass1</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ServletClass1</servlet-name>
        <url-pattern>/first.*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

first.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Test Page</title>
  </head>
  <body>
    <form name="f1" action="first" method="get">
      <input type="text" name=t/>
      <button value="Click" type="submit"></button>
    </form>
  </body>
</html>

ServletClass1.java

package com.test;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ServletClass1 extends HttpServlet 
{
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out= response.getWriter();  
        String msg = request.getParameter("t");
        out.println("the msg is"+msg);  
    }
}

1 个答案:

答案 0 :(得分:0)

您的<form action>网址需要与servlet映射的<url-pattern>匹配。现在它没有。修复您的servlet映射<url-pattern>,如下所示:

<url-pattern>/first</url-pattern>

另见:


对具体问题

无关,请确保您没有阅读过时的资源/书籍/教程。您的web.xml被声明为符合Servlet 2.4,已经差不多9年了。我们已经在Servlet 3.0上使用了2.5年。