I downloaded Apache Tomcat 6.0.2
And created a new server in Eclipse
- New -> Server
- Select «Tomcat v6.0 Server», Next
- Tomcat Installation Directory -> Where I unzipped Apache Tomcat 6.0.2
- 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
38.3k19 gold badges108 silver badges156 bronze badges
asked Jul 22, 2009 at 6:57
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
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.
- Firstly open the Server’s view in Eclipse. (Window >> Show View >> Servers).
- Double click on your Tomcat Server to open the Server Overview.
- Then set the Server Locations to Use Tomcat installation (takes control of Tomcat installation). Save the changes.
- 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 DoyleShane Doyle
1,0661 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
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
sourcerebelssourcerebels
5,1401 gold badge32 silver badges52 bronze badges
answered Jul 24, 2009 at 15:23
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_HOMEbinstartup.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
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:
In Eclipse, right click on server —> Properties —> Click Switch
Location —> Apply—>Ok
(This will switch the [workspace metadata]
location to the installed Tomcat location.)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
3,3029 gold badges27 silver badges50 bronze badges
answered Dec 16, 2016 at 9:55
1- double click on server
2- Make Sure You have switched correctly the directory for tomcat here
Before
After Fix
3- And Even if you do #2 above you may need do this here as well !
Again here !
answered Dec 19, 2017 at 20:20
shareefshareef
9,19513 gold badges58 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
69.5k35 gold badges181 silver badges252 bronze badges
answered Jul 6, 2022 at 18:04
стасевичстасевич
2782 silver badges10 bronze badges
I downloaded Apache Tomcat 6.0.2
And created a new server in Eclipse
- New -> Server
- Select «Tomcat v6.0 Server», Next
- Tomcat Installation Directory -> Where I unzipped Apache Tomcat 6.0.2
- 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
38.3k19 gold badges108 silver badges156 bronze badges
asked Jul 22, 2009 at 6:57
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
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.
- Firstly open the Server’s view in Eclipse. (Window >> Show View >> Servers).
- Double click on your Tomcat Server to open the Server Overview.
- Then set the Server Locations to Use Tomcat installation (takes control of Tomcat installation). Save the changes.
- 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 DoyleShane Doyle
1,0661 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
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
sourcerebelssourcerebels
5,1401 gold badge32 silver badges52 bronze badges
answered Jul 24, 2009 at 15:23
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_HOMEbinstartup.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
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:
In Eclipse, right click on server —> Properties —> Click Switch
Location —> Apply—>Ok
(This will switch the [workspace metadata]
location to the installed Tomcat location.)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
3,3029 gold badges27 silver badges50 bronze badges
answered Dec 16, 2016 at 9:55
1- double click on server
2- Make Sure You have switched correctly the directory for tomcat here
Before
After Fix
3- And Even if you do #2 above you may need do this here as well !
Again here !
answered Dec 19, 2017 at 20:20
shareefshareef
9,19513 gold badges58 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
69.5k35 gold badges181 silver badges252 bronze badges
answered Jul 6, 2022 at 18:04
стасевичстасевич
2782 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:
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:
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:
- Java servlets do not handle URL
- Servlet forwarding the resource does not exist
- 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.
As previous answers mentioned before, you’re using Spring Boot, which has its embedded Tomcat server under the hood. It’s the default behavior, but you may configure your Spring Boot project to use Netty or Undertow servers, please check more details here — Embedded Web Servers
So since you already have the Tomcat server, there is no need to configure it in your IDE. Also, worth mentioning that running a project from your IDE is not the best idea. Especially, when you’re describing your steps for reproducing the issue to someone else. Instead, you may run your Spring Boot project from the command line using the such command:
mvn spring-boot:run
By default, it’ll start your application on the 8080 port and you will be able to access your homepage at this URL: localhost:8080/home
For more details on running your Spring Boot application, you may check this document — Running your application
To run the Spring Boot project from your IntelliJ IDEA, you need to open the DemoApplication class (in your case), which has the main method. And on the left, there should be a play button for running your project. You can also configure it in the ‘Edit configurations’ menu by selecting the ‘Spring Boot’ item under the ‘Add new configuration’ menu.
Updated:
I’m using that you’re using macOS. To identify the process running on the 8080 port, which prevents you from starting your Spring Boot application, you may use such command:
sudo lsof -i :8080
This is the example output of this command from my machine, which has the Docker container running on the 8080 port:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
com.docke 3134 golovnya 174u IPv6 0xcaf3b5f3fb45111 0t0 TCP *:http-alt (LISTEN)
Here we’re interested in PID, which stands for the process identifier. It’s a unique id of the running application. In my case, the PID of the process running on the 8080 port is 3134. Knowing this, we may kill this process by the following command:
kill -9 <PID>
In my case it will look like this:
kill -9 3134
That’s all.
P.S. If it looks a bit complicated to your or you experience some issues, reloading your machine is always not a bad idea.
#java #spring #tomcat #intellij-idea #servlets
#java #весна #tomcat #intellij-идея #сервлеты
Вопрос:
Я сделал все в этом видео: но когда я печатаю: http://localhost:8080/spring-sample-1.0-SNAPSHOT/hello
Появляется эта ошибка:
HTTP Status 404 – Not Found
Type Status Report
Message The requested resource [/spring-sample-1.0-SNAPSHOT/hello] is not available
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Единственное, что я изменил, было в: tomcat/bin/setclasspath.bat, я добавил туда одну строку:
set JRE_HOME=C:Program FilesJavajre1.8.0_271
Потому что без этого сервер не запускается
Хорошо, итак, мое приложение действительно простое, я создал проект mvn на java 15, затем два класса:
Конфигурация:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Configuration
@ComponentScan({"app"})
@EnableWebMvc
public class Config extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
@Override
protected String[] getServletMappings() {
return new String[0];
}
}
Здравствуйте:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Hello {
@GetMapping("/hello")
public String get(){
return "Bycza zagroda!";
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pl.bykowski</groupId>
<artifactId>spring-sample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Затем я упаковал все в файл war и добавил его в менеджер tomcat здесь: файл WAR для развертывания
После этого я нажал /spring-sample-1.0-SNAPSHOT в модуле tomcat
а затем набрал привет в конце
Есть идеи, что происходит не так? :/
Комментарии:
1. Предоставленное вами видео не на английском языке. Кроме того, вы не должны ожидать, что мы посмотрим 19-минутное видео, чтобы понять, что вы сделали в качестве кода. Поэтому, пожалуйста, предоставьте достаточно кода, чтобы помочь нам понять ваш код и проблему, чтобы мы могли помочь
2. @UsemeAlehosaini Извините, теперь я это исправил
Ответ №1:
Я обнаружил проблему: в классе конфигурации вы указали неправильные значения для сопоставления сервлетов и класса конфигурации сервлета. Пожалуйста, измените класс конфигурации следующим образом:
@Configuration
@ComponentScan({"app"})
@EnableWebMvc
public class Config extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {Config.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Комментарии:
1. Большое тебе спасибо, брат <3 Создатель видео не упомянул об изменении методов переопределения
Ответ №2:
Прежде всего, я рекомендую установить переменную JAVA_HOME или JRE_HOME env для ОС. Для получения более подробной информации: https://confluence.atlassian.com/doc/setting-the-java_home-variable-in-windows-8895.html В любом случае изменение файлов tomcat — не очень хорошая идея 🙂
Для решения проблемы с недоступным URL, пожалуйста, проверьте:
для установленного tomcat:
- как правило, имя файла war — это имя контекста и часть URL-адреса (spring-sample-1.0-SNAPSHOT), но это имя может быть настроено в context.xml (Документация: https://tomcat.apache.org/tomcat-8.0-doc/config/context.html )
- откройте окно менеджера, как вы можете видеть на видео (http://localhost:8080/manager/html ) и найдите ссылку вашего веб-приложения
для встроенного tomcat:
- контекстный путь должен быть похож на artifactId в pom.xml
Комментарии:
1. В моей ситуации имя контекста — это имя файла .war. Также в ( localhost:8080/manager/html ) мое приложение отображается как ссылка: (/spring-sample-1.0-SNAPSHOT). artifactId = ‘spring-sample’ в pom.xml @заставка
2. Каков статус развертывания в tomcat для этого приложения war? Я думаю, что в вашем приложении есть ошибки во время процесса развертывания. И дополнительный вопрос: как вы собираетесь запускать приложение, которое скомпилировано на java 15, но tomcat был запущен под java 1.8? Вы получите исключение несовместимости версии java
Ответ №3:
@saver
Журнал из tomcat при развертывании:
21-Dec-2020 16:49:22.227 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war]
21-Dec-2020 16:49:24.113 INFO [http-nio-8000-exec-17] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
21-Dec-2020 16:49:24.138 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war] has finished in [1,907] ms
Итак, какие версии JRE и JDK я должен использовать?
Ответ №4:
@daniep kajoi вы должны установить путь на java 15 для tomcat или изменить атрибут maven.compiler.source в pom.xml на версии 1.8 — один из двух вариантов. И я вижу в вашем журнале, что ваш путь ‘spring-sample3-1.0-SNAPSHOT.war’
21-Dec-2020 16:49:22.227 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war]
21-Dec-2020 16:49:24.113 INFO [http-nio-8000-exec-17] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
21-Dec-2020 16:49:24.138 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war] has finished in [1,907] ms
попробуйте открыть url: http://localhost:8080/spring-sample3-1.0-SNAPSHOT.war/hello
Комментарии:
1. Я скачал Java 8, так что теперь все Java 8. И все та же проблема. Да, я знаю, я пытался создать новый проект с artifactId: spring-sample3.
Tomcat сообщает об ошибке, когда IntelliJ IDEA запускает проект: не удалось загрузить ресурс
В первый раз, когда я использую IntelliJ IDEA, я использовал eclipse раньше
Я с радостью готовился испытать новые инструменты разработки, но как только проект импорта начался, у меня возникла ошибка
После импорта проекта и настройки jdk tomcat запустится со следующей ошибкой:
Failed to load resource: the server responded with a status of 404 (Not Found)
Я думал, что это проблема с импортом Tomcat, поэтому долго менял.
Наконец обнаружил, что это была очень простая ошибка, решение заключается в следующем:
Нажмите 【Edit configurations…], выберите импортированный Tomcat, как показано ниже:
! ! нота! !
Имя хвоста URL в [server] должно совпадать с именем Application Context в [deployment]! ! (Расположение ① и ② на следующих двух рисунках)
Решено ~~ Кто бы мог подумать, что я чуть не переустановил его заново. .
Наконец-то я могу счастливо поиграть с IntelliJ IDEA
As previous answers mentioned before, you’re using Spring Boot, which has its embedded Tomcat server under the hood. It’s the default behavior, but you may configure your Spring Boot project to use Netty or Undertow servers, please check more details here — Embedded Web Servers
So since you already have the Tomcat server, there is no need to configure it in your IDE. Also, worth mentioning that running a project from your IDE is not the best idea. Especially, when you’re describing your steps for reproducing the issue to someone else. Instead, you may run your Spring Boot project from the command line using the such command:
mvn spring-boot:run
By default, it’ll start your application on the 8080 port and you will be able to access your homepage at this URL: localhost:8080/home
For more details on running your Spring Boot application, you may check this document — Running your application
To run the Spring Boot project from your IntelliJ IDEA, you need to open the DemoApplication class (in your case), which has the main method. And on the left, there should be a play button for running your project. You can also configure it in the ‘Edit configurations’ menu by selecting the ‘Spring Boot’ item under the ‘Add new configuration’ menu.
Updated:
I’m using that you’re using macOS. To identify the process running on the 8080 port, which prevents you from starting your Spring Boot application, you may use such command:
sudo lsof -i :8080
This is the example output of this command from my machine, which has the Docker container running on the 8080 port:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
com.docke 3134 golovnya 174u IPv6 0xcaf3b5f3fb45111 0t0 TCP *:http-alt (LISTEN)
Here we’re interested in PID, which stands for the process identifier. It’s a unique id of the running application. In my case, the PID of the process running on the 8080 port is 3134. Knowing this, we may kill this process by the following command:
kill -9 <PID>
In my case it will look like this:
kill -9 3134
That’s all.
P.S. If it looks a bit complicated to your or you experience some issues, reloading your machine is always not a bad idea.
- 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:
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:
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
Last Update:2017-05-24
Source: Internet
I’m going to make a POC, get an old project, use the war exploded to deploy to the native Tomcat (version 8.5)
When you start Tomcat by IntelliJ idea, you find that the login page of the system is http-status-404 error, and when you open http://localhost:8080 directly in the browser, you can open the Tomcat welcome page, It means Tomcat is up, but it doesn’t load the WebApps directory properly.
Even more strangely, the startup script under Tomcat’s Bin directory can start normally, either by double-clicking Startup.bat or by using Catalina.bat run under the directory’s CMD to start the project normally.
If you have a similar situation of friends, you can pay attention to the two startup mode at the start of the log environment variables, especially catalina_home.
Because the value of this variable is different on my machine when it is started in two ways, Catalina_home is the Tomcat directory where the bin is located when it is started by the bat script in the bin directory;
But when you start with IntelliJ idea, the value of the variable changes to: C:UsersCratical. Intellijidea2017.1systemtomcatunnamed_test-project_3_0_4
Two directories under the Conf folder, the folder inside the name and number of configuration files are the same, through the comparison, found in the Conf directory, Server.xml content There are some differences, note this line
autodeploy= «true» deployonstartup= » False «deployignore=» ^ (?! (manager) | (Tomee) $). * «>
Because in IntelliJ idea, a war format artifact can modify the location of the output directory, the default is the target folder under the current project root directory, if you use IntelliJ directly When idea started Tomcat, the WebApps directory under the Tomcat directory was unable to find the associated deployment folder.
IntelliJ idea is to achieve this goal by generating one of its own catalina_home, modifying the appbase in Server.xml.
Go back to that line of configuration, note that the deployignore property, my web directory name is exactly matched by the above regular expression, so Tomcat is directly ignored when loading, resulting in the 404 error.
The meanings of the various configurations in Tomcat Server.xml, see: http://www.importnew.com/17124.html
Intellij idea + Tomcat resolution for HTTP status 404 error
MichaelPak 0 / 0 / 0 Регистрация: 02.08.2011 Сообщений: 31 |
||||||||||||
1 |
||||||||||||
09.07.2014, 18:04. Показов 16933. Ответов 4 Метки нет (Все метки)
Проблема уже обсуждалась здесь, но никто так и не ответил. Создаю проект: Полсе этого сразу же пытаюсь запустить дефолтный index.jsp: В output следующее:
И браузер автоматически открывает страницу index.jsp, которую не может найти: И на последок конфигурации: Как и предыдущий новичок в этом деле, промучился около 4 часов. Подскажите, в чем может быть проблема? Добавлено через 5 минут
web.xml:
__________________ 0 |
4087 / 3821 / 745 Регистрация: 18.05.2010 Сообщений: 9,331 Записей в блоге: 11 |
|
09.07.2014, 20:01 |
2 |
Решениеjava.net.BindException: Address already in use Кто-то уже пользуется одним из тех портов, которые вы указали. Если в командной строке выполнить: 0 |
0 / 0 / 0 Регистрация: 02.08.2011 Сообщений: 31 |
|
09.07.2014, 23:46 [ТС] |
3 |
Вот такую штуку пишет: Миниатюры
0 |
2390 / 2216 / 564 Регистрация: 28.12.2010 Сообщений: 8,658 |
|
10.07.2014, 00:32 |
4 |
РешениеMichaelPak, найдите этот процесс в таск манагере (по айди) и убейте. 0 |
MichaelPak 0 / 0 / 0 Регистрация: 02.08.2011 Сообщений: 31 |
||||
10.07.2014, 12:45 [ТС] |
5 |
|||
Убить процесс с именем Java? Добавлено через 1 час 52 минуты Добавлено через 22 минуты
сервер заработал: 0 |
I’m having a problem with my first Web Application. I use IntelliJ as IDE and Tomcat as Webserver.
Every servlet I’ve tried to acces, throws an 404 Error. Even if I copy some youtube tutorials, which seems to work like a charm.
The button in the form sends me to: http://localhost:8080/IUBHQuiz/login
Can you tell me whats wrong? I am going nuts.
login.java
package com.example.IUBHQuiz;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
@WebServlet("/login")
public class login extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String email = request.getParameter("fmail");
String pass = request.getParameter("fpw");
if(email.equals("j") && pass.equals("j"))
{
RequestDispatcher rs = request.getRequestDispatcher("/main.jsp");
rs.forward(request, response);
}
else
{
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("/index.jsp");
rs.include(request, response);
}
out.close();
}
index.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>IUBH Quiz</title>
<link href="./resources/css/style.css" rel="stylesheet">
</head>
<body>
<div class="main">
<div class="image-container">
<img src="./resources/images/logo.png" alt="Logo">
</div>
<div class="Login">
<h1>Willkommen beim IUBH-Quiz!</h1>
<form action="login" method="post">
E-Mail:<input type="text" id="fmail" name="fmail"><br><br>
Passwort: <input type="password" id="fpw" name="fpw"><br><br>
<input type="submit" value="Log In" class="button">
</form>
</div>
<div class="Links">
<a href="#">Passwort vergessen</a>
<a href="#">Registrieren</a>
</div>
</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
Tomcat сообщает об ошибке, когда IntelliJ IDEA запускает проект: не удалось загрузить ресурс
В первый раз, когда я использую IntelliJ IDEA, я использовал eclipse раньше
Я с радостью готовился испытать новые инструменты разработки, но как только проект импорта начался, у меня возникла ошибка
После импорта проекта и настройки jdk tomcat запустится со следующей ошибкой:
Failed to load resource: the server responded with a status of 404 (Not Found)
Я думал, что это проблема с импортом Tomcat, поэтому долго менял.
Наконец обнаружил, что это была очень простая ошибка, решение заключается в следующем:
Нажмите 【Edit configurations…], выберите импортированный Tomcat, как показано ниже:
! ! нота! !
Имя хвоста URL в [server] должно совпадать с именем Application Context в [deployment]! ! (Расположение ① и ② на следующих двух рисунках)
Решено ~~ Кто бы мог подумать, что я чуть не переустановил его заново. .
Наконец-то я могу счастливо поиграть с IntelliJ IDEA
MichaelPak 0 / 0 / 0 Регистрация: 02.08.2011 Сообщений: 31 |
||||||||||||
1 |
||||||||||||
09.07.2014, 18:04. Показов 17274. Ответов 4 Метки нет (Все метки)
Проблема уже обсуждалась здесь, но никто так и не ответил. Создаю проект: Полсе этого сразу же пытаюсь запустить дефолтный index.jsp: В output следующее:
И браузер автоматически открывает страницу index.jsp, которую не может найти: И на последок конфигурации: Как и предыдущий новичок в этом деле, промучился около 4 часов. Подскажите, в чем может быть проблема? Добавлено через 5 минут
web.xml:
0 |
4088 / 3822 / 745 Регистрация: 18.05.2010 Сообщений: 9,331 Записей в блоге: 11 |
|
09.07.2014, 20:01 |
2 |
Решениеjava.net.BindException: Address already in use Кто-то уже пользуется одним из тех портов, которые вы указали. Если в командной строке выполнить: 0 |
0 / 0 / 0 Регистрация: 02.08.2011 Сообщений: 31 |
|
09.07.2014, 23:46 [ТС] |
3 |
Вот такую штуку пишет: Миниатюры
0 |
2392 / 2218 / 564 Регистрация: 28.12.2010 Сообщений: 8,662 |
|
10.07.2014, 00:32 |
4 |
РешениеMichaelPak, найдите этот процесс в таск манагере (по айди) и убейте. 0 |
MichaelPak 0 / 0 / 0 Регистрация: 02.08.2011 Сообщений: 31 |
||||
10.07.2014, 12:45 [ТС] |
5 |
|||
Убить процесс с именем Java? Добавлено через 1 час 52 минуты Добавлено через 22 минуты
сервер заработал: 0 |
#java #spring #tomcat #intellij-idea #servlets
#java #весна #tomcat #intellij-идея #сервлеты
Вопрос:
Я сделал все в этом видео: но когда я печатаю: http://localhost:8080/spring-sample-1.0-SNAPSHOT/hello
Появляется эта ошибка:
HTTP Status 404 – Not Found
Type Status Report
Message The requested resource [/spring-sample-1.0-SNAPSHOT/hello] is not available
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Единственное, что я изменил, было в: tomcat/bin/setclasspath.bat, я добавил туда одну строку:
set JRE_HOME=C:Program FilesJavajre1.8.0_271
Потому что без этого сервер не запускается
Хорошо, итак, мое приложение действительно простое, я создал проект mvn на java 15, затем два класса:
Конфигурация:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Configuration
@ComponentScan({"app"})
@EnableWebMvc
public class Config extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
@Override
protected String[] getServletMappings() {
return new String[0];
}
}
Здравствуйте:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Hello {
@GetMapping("/hello")
public String get(){
return "Bycza zagroda!";
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pl.bykowski</groupId>
<artifactId>spring-sample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Затем я упаковал все в файл war и добавил его в менеджер tomcat здесь: файл WAR для развертывания
После этого я нажал /spring-sample-1.0-SNAPSHOT в модуле tomcat
а затем набрал привет в конце
Есть идеи, что происходит не так? :/
Комментарии:
1. Предоставленное вами видео не на английском языке. Кроме того, вы не должны ожидать, что мы посмотрим 19-минутное видео, чтобы понять, что вы сделали в качестве кода. Поэтому, пожалуйста, предоставьте достаточно кода, чтобы помочь нам понять ваш код и проблему, чтобы мы могли помочь
2. @UsemeAlehosaini Извините, теперь я это исправил
Ответ №1:
Я обнаружил проблему: в классе конфигурации вы указали неправильные значения для сопоставления сервлетов и класса конфигурации сервлета. Пожалуйста, измените класс конфигурации следующим образом:
@Configuration
@ComponentScan({"app"})
@EnableWebMvc
public class Config extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {Config.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Комментарии:
1. Большое тебе спасибо, брат <3 Создатель видео не упомянул об изменении методов переопределения
Ответ №2:
Прежде всего, я рекомендую установить переменную JAVA_HOME или JRE_HOME env для ОС. Для получения более подробной информации: https://confluence.atlassian.com/doc/setting-the-java_home-variable-in-windows-8895.html В любом случае изменение файлов tomcat — не очень хорошая идея 🙂
Для решения проблемы с недоступным URL, пожалуйста, проверьте:
для установленного tomcat:
- как правило, имя файла war — это имя контекста и часть URL-адреса (spring-sample-1.0-SNAPSHOT), но это имя может быть настроено в context.xml (Документация: https://tomcat.apache.org/tomcat-8.0-doc/config/context.html )
- откройте окно менеджера, как вы можете видеть на видео (http://localhost:8080/manager/html ) и найдите ссылку вашего веб-приложения
для встроенного tomcat:
- контекстный путь должен быть похож на artifactId в pom.xml
Комментарии:
1. В моей ситуации имя контекста — это имя файла .war. Также в ( localhost:8080/manager/html ) мое приложение отображается как ссылка: (/spring-sample-1.0-SNAPSHOT). artifactId = ‘spring-sample’ в pom.xml @заставка
2. Каков статус развертывания в tomcat для этого приложения war? Я думаю, что в вашем приложении есть ошибки во время процесса развертывания. И дополнительный вопрос: как вы собираетесь запускать приложение, которое скомпилировано на java 15, но tomcat был запущен под java 1.8? Вы получите исключение несовместимости версии java
Ответ №3:
@saver
Журнал из tomcat при развертывании:
21-Dec-2020 16:49:22.227 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war]
21-Dec-2020 16:49:24.113 INFO [http-nio-8000-exec-17] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
21-Dec-2020 16:49:24.138 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war] has finished in [1,907] ms
Итак, какие версии JRE и JDK я должен использовать?
Ответ №4:
@daniep kajoi вы должны установить путь на java 15 для tomcat или изменить атрибут maven.compiler.source в pom.xml на версии 1.8 — один из двух вариантов. И я вижу в вашем журнале, что ваш путь ‘spring-sample3-1.0-SNAPSHOT.war’
21-Dec-2020 16:49:22.227 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war]
21-Dec-2020 16:49:24.113 INFO [http-nio-8000-exec-17] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
21-Dec-2020 16:49:24.138 INFO [http-nio-8000-exec-17] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [C:UsersDamianDesktopJAVAapache-tomcat-8.5.61webappsspring-sample3-1.0-SNAPSHOT.war] has finished in [1,907] ms
попробуйте открыть url: http://localhost:8080/spring-sample3-1.0-SNAPSHOT.war/hello
Комментарии:
1. Я скачал Java 8, так что теперь все Java 8. И все та же проблема. Да, я знаю, я пытался создать новый проект с artifactId: spring-sample3.
Я использую Intellij ultimate, чтобы запустить простой сервис. Структура проекта выглядит следующим образом:
Моя конфигурация кота выглядит следующим образом: [1110 ]
При запуске консоль не выдает ошибок:
/tmp/apache-tomcat-8.5.38/bin/catalina.sh run
[2019-02-24 11:24:53,412] Artifact InsbotTomcat:war: Waiting for server connection to start artifact deployment...
[2019-02-24 11:24:53,412] Artifact web:war exploded: Waiting for server connection to start artifact deployment...
24-Feb-2019 23:24:54.294 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/8.5.38
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built: Feb 5 2019 11:42:42 UTC
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number: 8.5.38.0
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name: Mac OS X
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version: 10.12.6
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture: x86_64
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home: /Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/jre
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version: 1.8.0_201-b09
24-Feb-2019 23:24:54.296 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor: Oracle Corporation
24-Feb-2019 23:24:54.297 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE: /Users/diyu/Library/Caches/IntelliJIdea2018.3/tomcat/Tomcat_8_5_38_InsbotTomcat
24-Feb-2019 23:24:54.297 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME: /private/tmp/apache-tomcat-8.5.38
24-Feb-2019 23:24:54.297 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/Users/diyu/Library/Caches/IntelliJIdea2018.3/tomcat/Tomcat_8_5_38_InsbotTomcat/conf/logging.properties
24-Feb-2019 23:24:54.297 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
24-Feb-2019 23:24:54.298 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote=
24-Feb-2019 23:24:54.298 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.port=1099
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.ssl=false
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.password.file=/Users/diyu/Library/Caches/IntelliJIdea2018.3/tomcat/Tomcat_8_5_38_InsbotTomcat/jmxremote.password
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcom.sun.management.jmxremote.access.file=/Users/diyu/Library/Caches/IntelliJIdea2018.3/tomcat/Tomcat_8_5_38_InsbotTomcat/jmxremote.access
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.rmi.server.hostname=127.0.0.1
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dorg.apache.catalina.security.SecurityListener.UMASK=0027
24-Feb-2019 23:24:54.300 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dignore.endorsed.dirs=
24-Feb-2019 23:24:54.301 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/Users/diyu/Library/Caches/IntelliJIdea2018.3/tomcat/Tomcat_8_5_38_InsbotTomcat
24-Feb-2019 23:24:54.301 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/tmp/apache-tomcat-8.5.38
24-Feb-2019 23:24:54.301 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/tmp/apache-tomcat-8.5.38/temp
24-Feb-2019 23:24:54.301 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/diyu/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
24-Feb-2019 23:24:54.457 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
24-Feb-2019 23:24:54.477 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
24-Feb-2019 23:24:54.494 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
24-Feb-2019 23:24:54.496 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
24-Feb-2019 23:24:54.497 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 591 ms
24-Feb-2019 23:24:54.527 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina]
24-Feb-2019 23:24:54.527 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.38
24-Feb-2019 23:24:54.537 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
24-Feb-2019 23:24:54.548 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
24-Feb-2019 23:24:54.549 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 52 ms
Connected to server
[2019-02-24 11:24:55,011] Artifact InsbotTomcat:war: Artifact is being deployed, please wait...
[2019-02-24 11:24:55,012] Artifact web:war exploded: Artifact is being deployed, please wait...
24-Feb-2019 23:24:58.220 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
[2019-02-24 11:24:58,277] Artifact InsbotTomcat:war: Artifact is deployed successfully
[2019-02-24 11:24:58,277] Artifact InsbotTomcat:war: Deploy took 3,266 milliseconds
[2019-02-24 11:24:58,342] Artifact web:war exploded: Artifact is deployed successfully
[2019-02-24 11:24:58,342] Artifact web:war exploded: Deploy took 3,330 milliseconds
24-Feb-2019 23:25:04.541 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/private/tmp/apache-tomcat-8.5.38/webapps/manager]
24-Feb-2019 23:25:04.573 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/private/tmp/apache-tomcat-8.5.38/webapps/manager] has finished in [32] ms
В то время как автоматически открывающаяся страница выглядит так:
Я также попробовал http://localhost:8080/web_war_exploded/index.html
, показывая тот же результат.
После Open Module Settings
я изменил конфигурацию так:
И это работает.
Ссылка
1 ответ
Проблема может заключаться в том, что каталогом развертывания является «webapps / manager» (/private/tmp/apache-tomcat-8.5.38/webapps/manager
), а не «webapps».
ответ дан Freddy
17.05.2019, 03:28
Ссылка
Теги
Похожие вопросы
I’m having a problem with my first Web Application. I use IntelliJ as IDE and Tomcat as Webserver.
Every servlet I’ve tried to acces, throws an 404 Error. Even if I copy some youtube tutorials, which seems to work like a charm.
The button in the form sends me to: http://localhost:8080/IUBHQuiz/login
Can you tell me whats wrong? I am going nuts.
login.java
package com.example.IUBHQuiz;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
@WebServlet("/login")
public class login extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String email = request.getParameter("fmail");
String pass = request.getParameter("fpw");
if(email.equals("j") && pass.equals("j"))
{
RequestDispatcher rs = request.getRequestDispatcher("/main.jsp");
rs.forward(request, response);
}
else
{
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("/index.jsp");
rs.include(request, response);
}
out.close();
}
index.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>IUBH Quiz</title>
<link href="./resources/css/style.css" rel="stylesheet">
</head>
<body>
<div class="main">
<div class="image-container">
<img src="./resources/images/logo.png" alt="Logo">
</div>
<div class="Login">
<h1>Willkommen beim IUBH-Quiz!</h1>
<form action="login" method="post">
E-Mail:<input type="text" id="fmail" name="fmail"><br><br>
Passwort: <input type="password" id="fpw" name="fpw"><br><br>
<input type="submit" value="Log In" class="button">
</form>
</div>
<div class="Links">
<a href="#">Passwort vergessen</a>
<a href="#">Registrieren</a>
</div>
</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
- 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:
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:
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.