我正在尝试构建一个 Java servlet,并且我已经按照我的教授给我们班级的指示做了所有事情,但是我遇到了一个奇怪的错误。
背景:我正在使用 Java EE Helios 和 Tomcat 7。
我在 Eclipse 中启动了一个新的动态 Web 项目,我创建了一个 index.jsp 页面,它只获取用户名并将其发送到 servlet,然后应该打印出 Hello, [username]。该代码是教授给我们的所有示例代码,并为我班上的其他人工作。
我制作了一个名为 ServletHome 的新 Servlet,它位于一个名为 servlets 的包中。
当我从 Eclipse 运行程序时,它可以正常启动 Tomcat,没有问题。我可以导航到 index.jsp 页面,它看起来不错。
问题是,当我填写我的姓名并按下“提交”按钮时,我收到一个 tomcat 404 错误消息:“请求的资源 (/MyFirstServlet/ServletHome) 不可用。”
有任何想法吗?
谢谢!!
--- 编辑:代码 ---
index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form action="ServletHome" method="POST">
First Name: <input type="text" name="firstName" size="20"><br>
Last Name: <input type="text" name="lastName" size="20"> <br>
<br> <input type="submit" value="Submit">
</form>
</body>
</html>
ServletHome.java:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHome extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletHome() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
}
/**
* The function that gets the name and returns an HTML file with Hello to them
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
//set type of output
response.setContentType("text/html;charset=UTF-8");
//get writer
PrintWriter out = response.getWriter();
//get first name
String firstName = request.getParameter("firstName").toString();
//get last name
String lastName = request.getParameter("lastName").toString();
//write the file
out.println("<html>");
out.println("<head>");
out.println("<title>Test Title</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Welcome, " + firstName + " " + lastName + "!</p>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
网页.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ServletHome</servlet-name>
<servlet-class>servlets.ServletHome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletHome</servlet-name>
<url-pattern>/servlets/*</url-pattern>
</servlet-mapping>
</web-app>