Tomcat 7 keeps giving me a 404. What am I doing wrong?

后端 未结 2 1051
长发绾君心
长发绾君心 2021-01-14 14:46

this is my first servlet ever. here is it\'s code.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Ch1Servlet extends Htt         


        
相关标签:
2条回答
  • 2021-01-14 15:13

    You should put servlet classes in a package. Whether packageless servlets works depend on the specific combination of an older Tomcat and JVM version. If you see this example in a book/tutorial, then it is surely far outdated.

    package com.example;
    
    // ...
    
    public class Ch1Servlet extends HttpServlet {
        // ...
    }
    

    You should have a /com/example/Ch1Servlet.java file. Compile it as follows

    javac -classpath /usr/share/tomcat7/common/lib/servlet-api.jar -d classes src/com/example/Ch1servlet.java
    

    (I however wonder what the common lib is doing there, this was typical for Tomcat 4.x/5.x, but it's not present since Tomcat 6. If you manually changed Tomcat's structure in order to follow the instructions of an outdated tutorial, undo it!)

    Put the com folder with the generated class by its entirity in /WEB-INF/classes folder of your webapp. So you must have a /WEB-INF/classes/com/example/Ch1Servlet.class.

    Then, edit your /WEB-INF/web.xml to specify the fully qualified name (FQN) of the servlet class in <servlet-class>:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        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_3_0.xsd"
        version="3.0" 
    >
        <servlet>
            <servlet-name>Chapter1 Servlet</servlet-name>
            <servlet-class>com.example.Ch1Servlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Chapter1 Servlet</servlet-name>
            <url-pattern>/Serv1</url-pattern>
        </servlet-mapping>
    </web-app>
    

    (please note that I fixed the root declaration as well to comply Tomcat 7 supported servlet version, it would otherwise fall back to least compatibility modus)

    0 讨论(0)
  • 2021-01-14 15:23

    You should config your ch1 context, in server.xml ,like this:

    <Context docBase="Your_web_apps_directory" path="/ch1" reloadable="false"/>
    
    0 讨论(0)
提交回复
热议问题