0

总而言之,我是 Java Web 开发的新手,我正在尝试在我的测试中实现一个 Servlet。但是我发现我创建的 Servlet 不起作用。我不知道我是否错过了什么。请帮我检查一下。谢谢。

到目前为止我所做的是:

  1. 使用选项 创建了一个Dynamic Web Project命名。SecondWebGenerate web.xml DD
  2. 在包下 添加了一个Servlet命名。我用值 和. 希望它适用于根目录下的所有 url 模式。HelloServletcom.example.servletsURL Mapping/HelloServlet/*

这是它的代码。

package com.example.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: HelloServlet
 *
 */
 public class HelloServlet extends javax.servlet.http.HttpServlet 
     implements javax.servlet.Servlet {

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public HelloServlet() {
        super();
    }       

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, 
         HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        response.getWriter().write("Hello, world!");
    }   

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, 
         HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        // TODO Auto-generated method stub
    }               
}

而且我还添加了一个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>My Title</title>
</head>
<body>
<% java.util.Date d = new java.util.Date(); %>
<h1>
Today's date is <%= d.toString() %> and this jsp page worked!
</h1>
</body>
</html>

我期望的是我希望在Hello world访问URL或. 但似乎不起作用。为什么?谢谢。index.jspHTMLhttp://localhost:8080/SecondWebhttp://localhost:8080/SecondWeb/index.jspHelloServlet

4

1 回答 1

1

我发现了问题,我必须ServletWeb.xml. 像下面的根元素下:

    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.example.servlets.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
于 2013-05-03T08:28:22.283 回答