很抱歉,如果这是一个常见的问题,但我会发疯的。 我开始使用在Ubuntu Server上运行的Tomcat进行JSP开发。我正在尝试运行我的第一个“Hello World”servlet,但没有成功。
我在服务器上有以下内容:
webapps
目录是:/var/lib/tomcat6/webapps/
webapps
我创建了context-root hello/
目录
hello/
包含index.html
和WEB-INF/
WEB-INF
包含web.xml
和classes/HelloServlet.class
这是index.html
:
<html>
<body>
Click to request the HelloServlet.
<form action = "/hello/helloworld" method = "get" >
<input type = "submit" value = "REQUEST" />
</form>
</body>
</html>
这是WEB-INF/web.xml
:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/hello/helloworld</url-pattern>
</servlet-mapping>
</web-app>
最后这是HelloServlet
的源文件:
// HelloServlet.java, a simple Hello World servlet.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter outputStream = response.getWriter();
outputStream.println("<html>");
outputStream.println("<head>");
outputStream.println("<title>Hello, World!</title>");
outputStream.println("</head>");
outputStream.println("<body>");
outputStream.println("Hello, world! This is my first servlet!");
outputStream.println("</body>");
outputStream.println("</html>");
outputStream.close();
}
}
问题在于,在客户端,只有http://localhost/hello/
(即index.html
页面)才有效。如果我单击表单提交按钮,则会出现http 404错误(资源不可用)。
可能在servlet-mapping中存在错误,形式和/或web.xml
,但我真的需要帮助来发现它。
答案 0 :(得分:4)
<url-pattern>/hello/helloworld</url-pattern>
您不应在servlet的URL模式中包含上下文路径。它已经相对于上下文根。
摆脱它。
<url-pattern>/helloworld</url-pattern>
无关,在servlet中编写HTML代码是一种非常糟糕的做法。因为应该使用JSP。另请参阅our own Servlets wiki page which contains sane Hello World examples。
答案 1 :(得分:1)
将上下文根添加到jsp操作,下面的更改可能适合您。
<form action = "/hello/hello/helloworld" method = "get" >
<input type = "submit" value = "REQUEST" />
</form>
答案 2 :(得分:1)
404可能导致:
答案 3 :(得分:0)
我花了很长时间才弄明白这一点。在我的情况下,我得到了404,因为我没有意识到Tomcat URL 区分大小写!
e.g:
http://server:8080/acme.MyPackage/DoStuff
... 404!
http://server:8080/acme.myPackage/DoStuff
...精细。
疯狂。