为什么servlet不起作用?

时间:2013-05-03 05:11:39

标签: java eclipse jsp servlets

所有,我是Java Web开发的新手,我正在尝试在我的测试中实现一个Servlet。但是我发现我创建的Servlet不起作用。我不知道我是否遗漏了什么。请帮我复习一下。谢谢。

到目前为止,我所做的是:

  1. 使用该选项创建了一个名为Dynamic Web Project的{​​{1}} SecondWeb
  2. 在软件包下添加了名为Generate web.xml DD的{​​{1}} Servlet。我使用值配置HelloServlet com.example.servletsURL Mapping。希望它适用于所有url模式 在根下。
  3. 这是代码。

    /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字符串添加到index.jsp响应HTML中。但似乎http://localhost:8080/SecondWeb不起作用。为什么?感谢。

1 个答案:

答案 0 :(得分:1)

我发现了这个问题,我必须在Servlet中添加Web.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>
相关问题