Ошибка 404 при запуске tomcat

I downloaded Apache Tomcat 6.0.2
And created a new server in Eclipse

  1. New -> Server
  2. Select «Tomcat v6.0 Server», Next
  3. Tomcat Installation Directory -> Where I unzipped Apache Tomcat 6.0.2
  4. Finish

Then I start the server and go to http://localhost:8080/ to see if it works. And I get a 404 error.

I’ve already googled it and tried to find a solution. But none of those remedies seem to work.

Any thoughts on what the problem is?

Stu Thompson's user avatar

Stu Thompson

38.4k19 gold badges110 silver badges156 bronze badges

asked Jul 22, 2009 at 6:57

hello_world_infinity's user avatar

2

From the top of my head, I thought Eclipse started the tomcat server without anything in it, i.e. no web applications. You have to ‘run’ or actually deploy something in that Eclipse Tomcat server so you won’t get the 404s.

The fact that you do get 404 error messages indicates that Tomcat actually IS running. If you shut it down from Eclipse, you won’t get those 404’s anymore ;)

answered Jul 22, 2009 at 7:10

drvdijk's user avatar

If your wanting to see your Tomcat Server Homepage then you will need to specify the server path and deploy path. The default is set to Use workspace metadata (does not modify your Tomcat installation).

How to do it.

  1. Firstly open the Server’s view in Eclipse. (Window >> Show View >> Servers).
  2. Double click on your Tomcat Server to open the Server Overview.
  3. Then set the Server Locations to Use Tomcat installation (takes control of Tomcat installation). Save the changes.
  4. Restart your Server and then go to localhost:8080. This should open the Apache Tomcat Homepage for your server.

Hope this helps!

answered Apr 14, 2012 at 20:46

Shane Doyle's user avatar

Shane DoyleShane Doyle

1,0761 gold badge12 silver badges16 bronze badges

The error 404 appears when Tomcat can’t find the localhost.ser file.
In order to get rid of this follow these steps:
1) In Eclipse, right click on server —> Properties —> Click Switch Location —> Apply—>Ok
(This will switch the [workspace metadata] location to the installed Tomcat location.)
2) Then go back to server, double click it. This will open Overview tab. Under this tab goto —>Server Location —> Select Use Tomcat Installation combo box.

Now close it, save it and try run your server and then rerun the URL.

answered May 1, 2012 at 20:20

Sonu's user avatar

SonuSonu

511 silver badge1 bronze badge

I agree to drvdijk.

Go to «Servers» window, then select your Tomcat instance. Double.click here you will see the «overview» window. Here you can click on «Open launch configuration» to see your Tomcat arguments («Arguments» tab).

Look for the system property «-Dwtp.deploy». This directory is where your Tomcat is looking for installed web applications, i think you don’t have ROOT.war application here. Isn’t it? :-)

Hope this will help you

answered Jul 22, 2009 at 7:35

sourcerebels's user avatar

sourcerebelssourcerebels

5,1501 gold badge32 silver badges52 bronze badges

answered Jul 24, 2009 at 15:23

Titi Wangsa bin Damhore's user avatar

The problem is just as drvdijk mentioned, in order to run a webapp on tomcat from eclipse, it needs to be «deployed» to it. This can be done by right clicking the tomcat server -> add and remove

Alternatively, you can try to startup your tomcat server outside of eclipse. Go to your command line and type

  $CATALINA_HOME\bin\startup.bat          (Windows)

  $CATALINA_HOME/bin/startup.sh           (Unix)

Where $catalina_home is the directory of where you installed tomcat

answered Jan 8, 2012 at 23:41

kumikoda's user avatar

kumikodakumikoda

6446 silver badges27 bronze badges

Launch your eclipse Run as administration:
For that right click on eclipse——> run as administration.
It works.

If it not works then again do same and then follow these steps:

  1. In Eclipse, right click on server —> Properties —> Click Switch
    Location —> Apply—>Ok
    (This will switch the [workspace metadata]
    location to the installed Tomcat location.)

  2. Then go back to server, double click it. This will open Overview
    tab. Under this tab goto —>Server Location —> Select Use Tomcat
    Installation
    combo box.

Now close it, save it and try run your server and then rerun the URL.

Panther's user avatar

Panther

3,3129 gold badges27 silver badges50 bronze badges

answered Dec 16, 2016 at 9:55

Ashish Anand's user avatar

1- double click on server
2- Make Sure You have switched correctly the directory for tomcat here

Before

enter image description here

After Fix
enter image description here

3- And Even if you do #2 above you may need do this here as well !

Again here !

enter image description here

answered Dec 19, 2017 at 20:20

shareef's user avatar

shareefshareef

9,28513 gold badges59 silver badges89 bronze badges

Also, notice if you have a duplicated WEB-INF in your path. Sometimes after update a maven project you may have this issue and Tomcat points to an empty folder.

Try to use Tomcat 9 Instead of Tomcat 10

Applications that run on Tomcat 9 and earlier will not run on Tomcat 10 without changes. Java EE based applications designed for Tomcat 9 and earlier may be placed in the $CATALINA_BASE/webapps-javaee directory and Tomcat will automatically convert them to Jakarta EE and copy them to the webapps directory. This conversion is performed using the Apache Tomcat migration tool for Jakarta EE tool which is also available as a separate download for off-line use.

Eric Aya's user avatar

Eric Aya

69.5k35 gold badges181 silver badges253 bronze badges

answered Jul 6, 2022 at 18:04

стасевич's user avatar

стасевичстасевич

2982 silver badges10 bronze badges

I downloaded Apache Tomcat 6.0.2
And created a new server in Eclipse

  1. New -> Server
  2. Select «Tomcat v6.0 Server», Next
  3. Tomcat Installation Directory -> Where I unzipped Apache Tomcat 6.0.2
  4. Finish

Then I start the server and go to http://localhost:8080/ to see if it works. And I get a 404 error.

I’ve already googled it and tried to find a solution. But none of those remedies seem to work.

Any thoughts on what the problem is?

Stu Thompson's user avatar

Stu Thompson

38.4k19 gold badges110 silver badges156 bronze badges

asked Jul 22, 2009 at 6:57

hello_world_infinity's user avatar

2

From the top of my head, I thought Eclipse started the tomcat server without anything in it, i.e. no web applications. You have to ‘run’ or actually deploy something in that Eclipse Tomcat server so you won’t get the 404s.

The fact that you do get 404 error messages indicates that Tomcat actually IS running. If you shut it down from Eclipse, you won’t get those 404’s anymore ;)

answered Jul 22, 2009 at 7:10

drvdijk's user avatar

If your wanting to see your Tomcat Server Homepage then you will need to specify the server path and deploy path. The default is set to Use workspace metadata (does not modify your Tomcat installation).

How to do it.

  1. Firstly open the Server’s view in Eclipse. (Window >> Show View >> Servers).
  2. Double click on your Tomcat Server to open the Server Overview.
  3. Then set the Server Locations to Use Tomcat installation (takes control of Tomcat installation). Save the changes.
  4. Restart your Server and then go to localhost:8080. This should open the Apache Tomcat Homepage for your server.

Hope this helps!

answered Apr 14, 2012 at 20:46

Shane Doyle's user avatar

Shane DoyleShane Doyle

1,0761 gold badge12 silver badges16 bronze badges

The error 404 appears when Tomcat can’t find the localhost.ser file.
In order to get rid of this follow these steps:
1) In Eclipse, right click on server —> Properties —> Click Switch Location —> Apply—>Ok
(This will switch the [workspace metadata] location to the installed Tomcat location.)
2) Then go back to server, double click it. This will open Overview tab. Under this tab goto —>Server Location —> Select Use Tomcat Installation combo box.

Now close it, save it and try run your server and then rerun the URL.

answered May 1, 2012 at 20:20

Sonu's user avatar

SonuSonu

511 silver badge1 bronze badge

I agree to drvdijk.

Go to «Servers» window, then select your Tomcat instance. Double.click here you will see the «overview» window. Here you can click on «Open launch configuration» to see your Tomcat arguments («Arguments» tab).

Look for the system property «-Dwtp.deploy». This directory is where your Tomcat is looking for installed web applications, i think you don’t have ROOT.war application here. Isn’t it? :-)

Hope this will help you

answered Jul 22, 2009 at 7:35

sourcerebels's user avatar

sourcerebelssourcerebels

5,1501 gold badge32 silver badges52 bronze badges

answered Jul 24, 2009 at 15:23

Titi Wangsa bin Damhore's user avatar

The problem is just as drvdijk mentioned, in order to run a webapp on tomcat from eclipse, it needs to be «deployed» to it. This can be done by right clicking the tomcat server -> add and remove

Alternatively, you can try to startup your tomcat server outside of eclipse. Go to your command line and type

  $CATALINA_HOME\bin\startup.bat          (Windows)

  $CATALINA_HOME/bin/startup.sh           (Unix)

Where $catalina_home is the directory of where you installed tomcat

answered Jan 8, 2012 at 23:41

kumikoda's user avatar

kumikodakumikoda

6446 silver badges27 bronze badges

Launch your eclipse Run as administration:
For that right click on eclipse——> run as administration.
It works.

If it not works then again do same and then follow these steps:

  1. In Eclipse, right click on server —> Properties —> Click Switch
    Location —> Apply—>Ok
    (This will switch the [workspace metadata]
    location to the installed Tomcat location.)

  2. Then go back to server, double click it. This will open Overview
    tab. Under this tab goto —>Server Location —> Select Use Tomcat
    Installation
    combo box.

Now close it, save it and try run your server and then rerun the URL.

Panther's user avatar

Panther

3,3129 gold badges27 silver badges50 bronze badges

answered Dec 16, 2016 at 9:55

Ashish Anand's user avatar

1- double click on server
2- Make Sure You have switched correctly the directory for tomcat here

Before

enter image description here

After Fix
enter image description here

3- And Even if you do #2 above you may need do this here as well !

Again here !

enter image description here

answered Dec 19, 2017 at 20:20

shareef's user avatar

shareefshareef

9,28513 gold badges59 silver badges89 bronze badges

Also, notice if you have a duplicated WEB-INF in your path. Sometimes after update a maven project you may have this issue and Tomcat points to an empty folder.

Try to use Tomcat 9 Instead of Tomcat 10

Applications that run on Tomcat 9 and earlier will not run on Tomcat 10 without changes. Java EE based applications designed for Tomcat 9 and earlier may be placed in the $CATALINA_BASE/webapps-javaee directory and Tomcat will automatically convert them to Jakarta EE and copy them to the webapps directory. This conversion is performed using the Apache Tomcat migration tool for Jakarta EE tool which is also available as a separate download for off-line use.

Eric Aya's user avatar

Eric Aya

69.5k35 gold badges181 silver badges253 bronze badges

answered Jul 6, 2022 at 18:04

стасевич's user avatar

стасевичстасевич

2982 silver badges10 bronze badges

Details
Written by  
Last Updated on 05 November 2019   |   Print  Email

In Java web development with Tomcat, it’s very often that you get HTTP 404 error like this:

tomcat-error-404

The error code is HTTP 404 (not found) and the description is:

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

This error means the server could not find the requested resource (JSP, HTML, images…) and returns HTTP status code 404. Most of the time, you can fix this error by correcting the URL. However, sometimes it’s not easy like that, making it is an annoying error.

Here I suggest some possible reasons and how to fix the error HTTP 404 in Java web development with Tomcat.

 

1. The URL is not handled by any Java servlets

You need to check URL mapping in your servlet classes to make sure the requested URL is actually handled by a servlet. For example:

@WebServlet("/view_book")
public class ViewBookServlet extends HttpServlet {
...
}

This servlet handles the URL /view_book. If the request URL is /view_books the server will raise HTTP 404 error. You can fix by either correcting the URL or correcting the URL mapping in the @WebServlet annotation.

In older Java web application, you have to check the web deployment descriptor file web.xml because a Java servlet can be mapped to URL via XML like this:

<servlet-mapping>
    <servlet-name>ViewBookServlet</servlet-name>
    <url-pattern>/view_book</url-pattern>
</servlet-mapping>

 

2. Java servlet forwarding to a resource that does not exist

In this case, the requested URL is handled by a Java servlet, but code in the servlet forwards to a resource (JSP, HTML…) which does not exist, as shown in the following screenshot:

tomcat-error-404-forwarding

The code in the servlet class would look like this:

String registerForm = "frontend/registerform.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(registerForm);
dispatcher.forward(request, response);

You can fix by correcting the forward path in the servlet, and make sure that the forwarded resource does actually exist in the given path.

 

3. URL is case-sensitive

Note that Tomcat treats URL as case-sensitive, for instance /Register is different than /register. So you need to check and use correct case for the letters in request URL.

Also pay attention to the webapp name in the URL, for instance http://localhost:8080/BookstoreWebsite/ is different than http://localhost:8080/BookStoreWebsite/

TIP: in Eclipse, you can right click on the project, then click Run As > Run on Server, the IDE will always use the correct name of the web application.

Finally, you should not let the user see the raw HTTP 404 error page rendered by the server. Instead, you should design your own user-friendly 404 error page – follow this tutorial: How to Handle Error for Java web applications.

You can also watch the video version below:

 

Other Java Servlet Tutorials:

  • Java Servlet Quick Start for beginners (XML)
  • Java Servlet for beginners (annotations)
  • Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
  • Handling HTML form data with Java Servlet
  • Java File Download Servlet Example

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

This error indicates that the server could not find the desired resource. This resource can be any file such as JSP, HTML, or image resource. Usually, the resource is present, but it is referenced incorrectly. In most cases, you can fix this by correcting the URL. Here are three strategies you can use to look for errors:

  1. Java servlets do not handle URL
  2. Servlet forwarding the resource does not exist
  3. URL is case-sensitive

1. Java servlets do not handle URL

Your @Webservlet() may handle for URL/name; however, the URL requested may be URL/this_name (different reference). You can fix this by correcting the reference URL or URL mapping.

In code, it may look something like this:

@WebServlet("/name")
public class Name extends HttpServlet {
...
}

However, your website requested /this_name instead of /name. One way you can correct this is by changing /name to /this_name in your URL mapping.

2. Servlet forwarding the resource does not exist

Make sure that the forwarded resource exists. If the resource you are trying to reference is not named correctly, you may also run into this problem. For instance, you are referencing signupForm.jsp, but the name of the resource is signup_Form.jsp. In code it may look something like this:

String signupForm= "frontend/signupForm.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(signupForm);
dispatcher.forward(request, response);

You can fix this by correcting the servlet’s path which, in this case, would be to change signupForm.jsp to signup_Form.jsp.

3. URL is case-sensitive

If you typed the URL yourself, you might have mistyped it. Tomcat URLs are case-sensitive. For instance, signup is different than signUp. Make sure your URL is case-sensitive.

я совершенно новичок в написании Java-сервлета и изо всех сил пытаюсь получить простой HelloWorld пример правильной работы.

В Файл HelloWorld.класс java:

package crunch;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

я запускаю Tomcat v7.0, и уже прочитали аналогичные вопросы, с ответами, относящимися к изменению invoker на web.xml, этот раздел на самом деле не существует в моем, и когда я добавил его, та же проблема все еще произошла.

7 ответов


попробуйте это (если Java EE V6)

package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet(name="hello",urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

теперь достигните сервлета http://127.0.0.1:8080/yourapp/hello

где 8080-порт tomcat по умолчанию, а yourapp-имя контекста вашего applciation


вам определенно нужно сопоставить сервлет с некоторым URL-адресом. Если вы используете Java EE 6 (это означает, по крайней мере, Servlet API 3.0), то вы можете аннотировать свой сервлет как

@WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
     //rest of the class

тогда вы можете просто пойти в localhost:8080/yourApp/hello и значение должно отображаться. Если вы не можете использовать Servlet 3.0 API, вам нужно зарегистрировать этот сервлет в как

<servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

написание Java сервлетов легко, если вы используете Java EE 7

@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("Hello World");
   out.flush();
  }
}

начиная с сервлета 3.0

хорошей новостью является то, что дескриптор развертывания больше не требуется!

читать учебник для Java-Сервлетов.


Это может быть связано с тем, что вы создали свой .ОСП или .html-файл в WEB-INF вместо WebContent.

решение: просто замените файлы, которые есть в папке WEB-INF в папку Webcontent и попробуйте выполнить то же самое — вы получите соответствующий вывод


для тех, кто застрял с «запрошенный ресурс недоступен» в Java EE 7 и динамическом веб-модуле 3.x, возможно, это может помочь: мастер «создать сервлет» в Eclipse (протестирован на Марсе) не создает @Path аннотация для класса сервлета, но я должен был включить его для успешного доступа к открытым методам.


вы должны пользователь ../../имя_проекта/именем.jsp в вашем действии attr. и href

../ = содержит текущую папку simple (demo.проект.имя файла.jsp)

сервлет может быть вызван только с 1 косой чертой вперед к имени вашего проекта..


моя проблема была в . В одном <servlet-mapping> внутри была ошибка <url-pattern>: забыл добавить / перед url.


Понравилась статья? Поделить с друзьями:
  • Ошибка 404 результаты егэ
  • Ошибка 404 шевроле авео т250
  • Ошибка 404 трек
  • Ошибка 404 трейлер на русском
  • Ошибка 404 тильда шаблон