浏览器显示404错误

时间:2014-02-07 12:19:17

标签: java servlets

我是servlet的新手,并使用eclipse创建我的第一个servlet。我已经创建了Index.html,Login.java和WelcomeServlet.java。但每当我试图访问使用

localhost:8080/ServletExample/

它显示404错误。这是代码..

的index.html

<form action="Login" method="post">  
Name:<input type="text" name="userName"/><br/>  
Password:<input type="password" name="userPass"/><br/>  
<input type="submit" value="login"/>  
</form>

Login.java

public class Login extends HttpServlet {  

    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  

        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  

        String n=request.getParameter("userName");  
        String p=request.getParameter("userPass");  

        if(p.equals("servlet")) {  
            RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");  
            rd.forward(request, response);  
        } else {  
            out.print("Sorry UserName or Password Error!");  
            RequestDispatcher rd=request.getRequestDispatcher("/index.html");  
            rd.include(request, response);  
        }  
    }  
}  

WelcomeServlet.java

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

public class WelcomeServlet extends HttpServlet {  

    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  

        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  

        String n=request.getParameter("userName");  
        out.print("Welcome "+n);  
    }  
}

的web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app>  
    <servlet>  
        <servlet-name>Login</servlet-name>  
        <servlet-class>Login</servlet-class>  
    </servlet>  
    <servlet>  
        <servlet-name>WelcomeServlet</servlet-name>  
        <servlet-class>WelcomeServlet</servlet-class>  
    </servlet>  

    <servlet-mapping>  
        <servlet-name>Login</servlet-name>  
        <url-pattern>/Login</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>WelcomeServlet</servlet-name>  
        <url-pattern>/WelcomeServlet</url-pattern>  
    </servlet-mapping>  

    <welcome-file-list>  
        <welcome-file>index.html</welcome-file>  
    </welcome-file-list>  
</web-app>  

3 个答案:

答案 0 :(得分:1)

package java.io;

为什么你把这行放在WelcomeServlet.java中。

答案 1 :(得分:0)

您正在映射到&#39; WelcomeServlet&#39;不是&#39; ServletExample&#39;。

尝试访问localhost:8080 / WelcomeServlet

编辑:不应该是一个尾随斜线,对不起!

答案 2 :(得分:-2)

确保您的项目名称是Servlet示例。

本地主机:8080 / ServletExample / index.html中