日期:2014-05-18  浏览次数:20788 次

为什么增加了package语句,servlet就不能执行(eclispe小论坛的高手都出去散步了)
为什么使用了package语句,servlet在保存时eclipse相应的目录都打上了红叉,并且不能执行servlet.  
Java code

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

public class TestServlet extends HttpServlet
{
    protected void doGet (HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
    {
        PrintWriter out=response.getWriter();
        out.println("<html><body><h1>welcome to JavaWorld</h1></body></html>");
        out.flush(); 
    }
    
}


web.xml是这样部署的:
XML code

<servlet>
    <servlet-name>Test</servlet-name>
    <display-name>Test</display-name>
    <description>A test servlet</description>
    <servlet-class>test.TestServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/Test</url-pattern>
</servlet-mapping>

    

  servlet源文件在web-inf下的src中,自动编译时eclipse界面相应的目录都打上了红叉,(我将生成的class文件复制放在了web-inf下class文件夹中的test下)。
  servlet文件执行错误。 
java.lang.NoClassDefFoundError: test/TestServlet (wrong name: TestServlet) 

  将servlet中的package语句去掉,并修改web.xml。便能成功执行servlet.
  为什么有了package语句就出错呢?



------解决方案--------------------
你src有test这个包么?
------解决方案--------------------
1 java文件放入test文件夹下(需要新建这个文件夹,和包名一致)

2 加入package test

3 web.xml中改成test.XXX
------解决方案--------------------
朋友,我没看出问题,我只能说,你的类可能没有编译成功,用翻遍一的软件看看你的class文件里有test包吗?
我刚安你的配置运行了一遍也一切ok.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>test.TestServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/Test</url-pattern>
</servlet-mapping>
</web-app>

package test;

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 TestServlet extends HttpServlet {
protected void doGet (HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println("<html><body><h1>welcome to JavaWorld</h1></body></html>");
out.flush(); 
}
}