Java Servlet 404错误

时间:2012-05-06 13:51:49

标签: servlets http-status-code-404

我的系统有Tomcat 7,所有文件都在webapps下。文件结构是

webapps / WelcomeForm / web / WelcomeForm.html

WEB-INF / web.xml

lib / classes / hello / HelloWorldServlet.java HelloWorldServlet.class

网络文件夹包含WelcomeForm.html。

WEB-INF拥有web.xml。

lib拥有servlet-api.jar和

类包含HelloWorldServlet.java。

html文件运行正常但我无法运行Java文件,因为它返回消息:

HTTP Status 404 - /hello

type Status report

message /hello

description The requested resource (/hello) is not available.

文件的代码如下:

WelcomeForm.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Welcome Form</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
           <form method="POST" action="/hello">
        <font size="10" color="red">Hello World!</font><BR>

     Type your first name and click submit button <input TYPE=TEXT NAME="username" SIZE=20>
            <P><input type="submit" value="Submit">


       </form> 

    </body>
</html>

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>hello.HelloWorldServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

HelloWorldServlet.java

package hello;

import java.io.IOException; 
import javax.servlet.ServletException; 
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import java.io.PrintWriter;

public class HelloWorldServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

      doPost(request,response);
      }

   public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    String name = request.getParameter("username");
    PrintWriter out = response.getWriter();
    out.write("Your Name is :" );
    out.print(name);

  }    
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

检查浏览器网址。你缺少背景。

假设您说,您正在http://localhost:8080/test/index.jsp运行,其中test是您的上下文路径。

所以,当调用Servlet时,它应该像http://localhost:8080/test/hello

在你的情况下,它不是那样的。

因此,添加cotextpath将解决您的问题。

e.g。 action="<%=request.getContextPath()%>/hello"

或者你可以使用

e.g。 action="hello"

因此,当您向action添加“/”时,请始终添加上下文路径。