I am creating simple servlet and deploying it in tomcat server but I am getting the following error:
HTTP Status 500 — Error instantiating servlet class pkg.coreServlet
File Structure on the tomcat server:
webapps
|
- aarya
|
- WEB-INF
|
-web.xml
-src(folder)
|
-pkg
|
-coreServlet.class
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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>aaryaservlet</servlet-name>
<servlet-class>pkg.coreServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>aaryaservlet</servlet-name>
<url-pattern>/coreServlet</url-pattern>
</servlet-mapping>
</web-app>
coreServlet.java:
package pkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class coreServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("this is First servlet Example ");
}
}
url I am giving is http://localhost:8080/aarya/coreServlet
I try by restarting tomcat but I am getting same error. Where I am doing wrong?
Im trying to create a RESTful web app and Im running into a Error 500 I’ve looked around at some answers and tried out the solutions with no avail.
Java Serverlet code
package org.some.package.tohere;
import java.util.List;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/somepath")
public class Analysis {
@POST
public String ClassName(@FormParam("inputArray[]") List<String> datalist) {
// Results results=Send to other
// ResultstoFirebase
return "Woooooo";
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
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">
<display-name>Project Name</display-name>
<welcome-file-list>
<welcome-file>test.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Name</servlet-name>
<servlet-class>>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.some.package.tohere;</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ProjectName</servlet-name>
<url-pattern>/analysis/* </url-pattern>
</servlet-mapping>
</web-app>
Javascript
function callGeneSpotService(inputArray)
{
var location =window.location.href+"analysis/somepath"
//Results should be the encrypted job id to be able to access the results on the web page.
var results = $.post(location,{inputArray:inputArray},function(response){
})
.done(function(results)
{
alert(results);
//alert("Now Processing, please check back in the results section with your job id in a few moments: "+ results);
})
.fail(function(results)
{
alert("Something went wrong please contact the systems administrator for help");
})
}
Error Stack
javax.servlet.ServletException: Error instantiating servlet class >com.sun.jersey.spi.container.servlet.ServletContainer
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.ClassNotFoundException: >com.sun.jersey.spi.container.servlet.ServletContainer
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
Not sure what else would help answer the question but I would be happy to provide
Here’s the issue: I had a few projects with JSP servlets running with NetBeans 8.2. When I tried to run them in NetBeans 12.1 at a different computer, I have the error: javax.servlet.ServletException: Error instantiating servlet class.
I’ve tried to create a new web application from zero, but I still get the same error. I’ve also tried to downgrade from JDK 15 to JDK 1.8 (which worked well for me before), but doesn’t worked. I’ve even tried to upgrade from Tomcat 7 to Tomcat 9, and also switched to GlassFish, but I got the same problem.
I’ve been searching in Internet for hours looking for a solution, but I couldn’t find anyone. What could be the matter? I’ve also seen a few cuestions in StackOverflow with a similar issue but it didn’t help.
Вот мой код:
miServlet.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package prueba;
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;
/**
*
* @author 54113
*/
public class miServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet miServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet miServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.setContentType("text/html;charser=UTF-8");
PrintWriter out = response.getWriter();
out.println("Hola");
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
index.jsp:
<%--
Document : index
Created on : 12 dic. 2020, 00:06:47
Author : 54113
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<h4>Haga click <a href="miServlet"> aqui </a> </h4>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<servlet>
<servlet-name>miServlet</servlet-name>
<servlet-class>prueba.miServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>miServlet</servlet-name>
<url-pattern>/miServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path=""/>
Вот сообщения об ошибках:
С Tomcat 7:
(Примечание. Ошибка при создании экземпляра сервлета означает Ошибка при создании экземпляра класса сервлета, а ошибка внутреннего сервера не выполняется. сервер обнаружил внутреннюю ошибку, которая помешала ему выполнить этот запрос. Causa raíz означает «Основная причина»).
Estado HTTP 500 – Internal Server Error
Tipo Informe de Excepción
mensaje Error instanciando clase de servlet [prueba.miServlet]
Descripción El servidor encontró un error interno que hizo que no pudiera rellenar este requerimiento.
excepción
javax.servlet.ServletException: Error instanciando clase de servlet [prueba.miServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2531)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2520)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
causa raíz
java.lang.RuntimeException:
prueba.miServlet.<init>(miServlet.java:1)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2531)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2520)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
nota La traza completa de la causa de este error se encuentra en los archivos de registro del servidor.
Apache Tomcat/7.0.107
С Tomcat 9:
Estado HTTP 500 – Internal Server Error
Tipo Informe de Excepción
mensaje Error instanciando clase de servlet [prueba.miServlet]
Descripción El servidor encontró un error interno que hizo que no pudiera rellenar este requerimiento.
excepción
javax.servlet.ServletException: Error instanciando clase de servlet [prueba.miServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
causa raíz
java.lang.RuntimeException:
prueba.miServlet.<init>(miServlet.java:1)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
nota La traza completa de la causa de este error se encuentra en los archivos de registro del servidor.
Apache Tomcat/9.0.41
Со GlassFish:
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class prueba.miServlet
root cause
com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class prueba.miServlet
root cause
java.lang.RuntimeException:
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 5.0.1 logs.
GlassFish Server Open Source Edition 5.0.1
Finally, here’s the project’s structure:
Большое спасибо!
Лучшее
Leandro
Содержание
- javax.servlet.ServletException: Error instantiating servlet class
- Error instantiating servlet class
- javax.servlet.ServletException: Error instantiating servlet class JavaMailS
- Error instantiating the servlet class
javax.servlet.ServletException: Error instantiating servlet class
I am having a following error when a request is made to my Login servlet.
description The server encountered an internal error () that prevented it from fulfilling this request.
javax.servlet.ServletException: Error instantiating servlet class udit.Login
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:556)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:401)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:619)
java.lang.NoClassDefFoundError: udit/Login (wrong name: Login)
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
java.lang.ClassLoader.defineClass(ClassLoader.java:616)
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2778)
org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1139)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1633)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1511)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:556)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:401)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:619)
PLZZ Suggest me what am i doing wrong
I compiled my servlet sucessfully so problem should not be with coding
I think that some jar files may be required BUT EVEN IF I DO THEN PLZZZ TEMME WHICH ALL JAR FILES ARE REQUIRED FOR SERVLETS AND JDBC TO WORK PROPERLY. I AM USING TOMCAT (latest). I hav set all the classpaths and other environment variables. PLZZ HELP ME OUT>.
Источник
Error instantiating servlet class
Please help me I just can’t find what exactly i’m missing in my code. it’s been three days i’m stuck on it. Please look into it. Also when I first wrote this program it was working and later I was facing issue with get method. i.e post was working but get was not working. Now nothing is working.
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Error instantiating servlet class [com.emandi.loginServlet]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Error instantiating servlet class [com.emandi.loginServlet]
Root Cause
java.lang.ClassNotFoundException: com.emandi.loginServlet
Dave Tolls wrote: How are you compiling and deploying this?
Because that error implies the servlet is not being deployed as part of your app.
Actually, that message can come when there’s an exception thrown by construction code.
I would like to see a stack trace.
Blitzlügen — Lies or information broadcast, but when called out the broadcaster does little or nothing is done to correct them, thus allowing those who wish to believe to accept them as truth.
Lügensturm — A barrage of Blitzlügen fired in such quick succession that it is essentially impossible to correct them all.
Источник
javax.servlet.ServletException: Error instantiating servlet class JavaMailS
I’m using javamail-1.3.1, Tomcat 4.0 with j2sdk1.4.2_04.
With a main class, I was able to mail successfully, but trying to use the class from Servlet, gives me all kinds of problems with Sealed Jar files.
Now I’m trying to implement the example Servlet. The Servlet code is below, I only cleaned the deprecated functions from the example and comented the //import javax.activation.*; line.
I get the following error:
javax.servlet.ServletException: Error instantiating servlet class JavaMailServlet
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:912)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:668)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:653)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:404)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:356)
at Validar.vValidar(Validar.java:150)
at Validar.service(Validar.java:24)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:404)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:356)
at Entrada.service(Entrada.java:95)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:509)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:594)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
at java.lang.Thread.run(Unknown Source)
/*
* @(#)JavaMailServlet.java 1.5 01/05/23
*
* Copyright 1998, 1999 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* — Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* — Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided «AS IS,» without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
* SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION
* OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
* SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
* FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.*;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
//import javax.activation.*;
/**
* This is a servlet that demonstrates the use of JavaMail APIs
* in a 3-tier application. It allows the user to login to an
* IMAP store, list all the messages in the INBOX folder, view
* selected messages, compose and send a message, and logout.
*
* Please note: This is NOT an example of how to write servlets!
* This is simply to show that JavaMail can be used in a servlet.
*
* For more information on this servlet, see the
* JavaMailServlet.README.txt file.
*
* For more information on servlets, see
* * http://java.sun.com/products/java-server/servlets/index.html
*
* @author Max Spivak
*/
public class JavaMailServlet extends HttpServlet
<
String protocol = «imap»;
String mbox = «INBOX»;
/**
* This method handles the «POST» submission from two forms: the
* login form and the message compose form. The login form has the
* following parameters: hostname , username ,
* and password . The send parameter denotes
* that the method is processing the compose form submission.
*/
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException <
// get the session
HttpSession ssn = req.getSession(true);
String send = req.getParameter(«send»);
String host = req.getParameter(«hostname»);
String user = req.getParameter(«username»);
String passwd = req.getParameter(«password»);
URLName url = new URLName(protocol, host, -1, mbox, user, passwd);
ServletOutputStream out = res.getOutputStream();
res.setContentType(«text/html»);
out.println(» «);
if (send != null) <
// process message sending
send(req, res, out, ssn);
Источник
Error instantiating the servlet class
Hello,
I boque on a simple servlet that I can not invoke, with appal of a JSP page. I have tried everything :
— parameters of the web.xml
— JSP
here is my code:
Philippe Ponceblanc wrote: in /src/webcart/WebCartServlet
Philippe Ponceblanc wrote: no, in the package webcart
Well, «src» is clearly a source directory, is it not?
Regardless, the class file needs to be inside WEB-INF/classes/webcart; is that where it is? Or is it in a jar file that contains all your classes? If so, that would go into WEB-INF/lib
Philippe Ponceblanc wrote: eclipse == /src/webcart/WebCartServlet.class
That’s not Tomcat.
That’s your IDE.
How are you deploying your web application to Tomcat?
Also, what Tomcat is it? Is it embedded as part of Eclipse or standalone?
Philippe Ponceblanc wrote: eclipse == /src/webcart/WebCartServlet.class
That’s not Tomcat.
That’s your IDE.
How are you deploying your web application to Tomcat?
Also, what Tomcat is it? Is it embedded as part of Eclipse or standalone?
These are the important questions. You need to understand what a WAR is and how it is used.
Blitzlügen — Lies or information broadcast, but when called out the broadcaster does little or nothing is done to correct them, thus allowing those who wish to believe to accept them as truth.
Lügensturm — A barrage of Blitzlügen fired in such quick succession that it is essentially impossible to correct them all.
I’m using tomcat 8.5, I generated a project as follows:
WEB-INF / classes / WebCart / WebCartServlet.java
likewise I added the jsp and the web.xml
now I have a 404 error!
WEB-INF / classes / WebCart / WebCartServlet.java
1) The package name is «webcart», not «WebCart».
2) That’s where WebCartServlet.class should be, not WebCartServlet.java.
project -Web-INF/classes
— webcart
— Cart.java
— WebCartServlet.java
— Meta-INF
— context.xml
— WEB-INF
— classes
— webcart
— Cart.java
-WebCartServelet.java
— panier.jsp
— web.xml
Tim Moores wrote: A source file does no good in WEB-INF/classes — that’s were the class file needs to be.
I follow a certification EE java, but it is this exercise that is imposed.
It starts in this form previously written.
how can i edit my .class files instead of .java
Tim Moores wrote: No editing — you compile the .java file which results in a .class file. The IDE does that for you, but it’s possible it doesn’t put the class files where they need to be. But after compilation they should be somewhere in the project folder, provided there were no errors.
I have no more error after compiling with Tomcat, I can not find the files.class!
Should you add a «target» directory for the tomcat?
to generate .class files in the «target» directory?
No, you must build a WAR and deploy the WAR to Tomcat.
You’re trying to let your IDE (Eclipse) do all the thinking for you. If you understood how Java webapps and webapp servers work, you could make everything work without using Eclipse at all.
In fact, you have to do so in the Real World. No sane IT shop is going to run an IDE on a production server machine.
Blitzlügen — Lies or information broadcast, but when called out the broadcaster does little or nothing is done to correct them, thus allowing those who wish to believe to accept them as truth.
Lügensturm — A barrage of Blitzlügen fired in such quick succession that it is essentially impossible to correct them all.
Hello,
I installed my project in the webapps directory of tomcat,
I have trouble understanding between the compile command and the deployment in tomcat my directory is «/opt/apache-tomcat-8.5.34/webapps/fun/exo103/».
at the moment my servlet does not display a JSp page via the doGet method, but I have a 404 error!
how to differentiate the command >> javac myservlet
how to deploy in tomcat >> catalina
First, you don’t install the «project» into Tomcat. As I said, Eclipse is not going to be around on a production Tomcat server. You only install the WAR into Tomcat. Tomcat doesn’t care about and cannot use Eclipse projects. Or IntelliJ projects. Or Netbeans projects. et cetera.
The WAR can be in the form of a WAR file or an unzipped («exploded») WAR. By default, Tomcat will take WAR files found in the Tomcat webapps directory and explode them into directories having the same base name as the WAR file’s name. So mywebapp.war explodes to directory «mywebapp» and the webapp’s URL context name would be «/mywebapp».
You cannot deploy WARs into sub-directories of the webapps directory. Only into the webapps directory itself. Tomcat would treat a file named TOMCAT_HOME/webapps/fun/exo103/myjsp.jsp as being deployed in the webapp whose context name was «fun» and the JSP would be accessible via the URL http://localhost:8080/fun/exo101/myjsp.jsp». It would not see that as a webapp named «exo101» — exo101 would simply be seen as a subdirectory of the «fun» webapp.
Blitzlügen — Lies or information broadcast, but when called out the broadcaster does little or nothing is done to correct them, thus allowing those who wish to believe to accept them as truth.
Lügensturm — A barrage of Blitzlügen fired in such quick succession that it is essentially impossible to correct them all.
Источник
javax.servlet.ServletException: Servlet execution threw an exception
В проекте maven большая часть причины этой ошибки servet заключается в том, что при запуске maven область действия servlet-api в Dependencies по умолчанию, не задана как предоставленная, и операция конфликтует с servlet-api, поставляемым с Tomcat. Итак, установите сервлет-api, импортированный проектом, на предоставленный.
Проект Maven не может скомпилировать решение jsp: невозможно скомпилировать класс для JSP
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 1 in the generated java file
The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files
Моя среда компиляции: JDK — 1.8, IDE — eclipse 4.7, веб-сервер — Tomcat 9.0, maven — 3.5.0, после настройки среды введите команду tomcat: run, а затем сообщите org.apache.jasper.JasperException: Unable для компиляции класса для ошибки JSP.
1. Невозможность компиляции должна быть причиной того, почему пакеты servlet-api и jsp-api не были импортированы, а затем в файл pom были добавлены пакеты servlet-api и jsp-api. Чтобы предотвратить конфликты пакетов, его необходимо изменить на предоставленный. , Конкретная операция такая же, как указано выше.
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
После добавления он все еще не работал, и тогда я начал искать Ду Нянга. Я так давно застал как новичок.
2. Eclipse по умолчанию использует собственный jre, и нам нужно заменить его на загруженный JDK. Добавьте загруженный JDK в Window-> Preference-> Java-> Installed JREs и удалите jre, который поставляется с eclipse.
Я закончил, я обнаружил, что моя версия — 1.8, но она все еще не работает!
Головная боль!
3. Абсолютный убийца! Переведите все содержимое ошибки! Конечно, мой английский отморозок должен пользоваться переводческой программой.
Неожиданно нашел!
, черт возьми! Он не работает на моем Tomcat!
Оказывается, maven по умолчанию использует Tomcat6, но я использую JDK1.8. Tomcat6 не может использоваться с JDK1.8. Просто увеличьте версию Tomcat.
Используйте подключаемый модуль maven Tomcat7: добавьте следующий код в файл pom:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
Предполагается, что вы также можете решить эту проблему сейчас.
Спасибо за просмотр и вместе добиваемся прогресса!
Here’s the issue: I had a few projects with JSP servlets running with NetBeans 8.2. When I tried to run them in NetBeans 12.1 at a different computer, I have the error: javax.servlet.ServletException: Error instantiating servlet class.
I’ve tried to create a new web application from zero, but I still get the same error. I’ve also tried to downgrade from JDK 15 to JDK 1.8 (which worked well for me before), but doesn’t worked. I’ve even tried to upgrade from Tomcat 7 to Tomcat 9, and also switched to GlassFish, but I got the same problem.
I’ve been searching in Internet for hours looking for a solution, but I couldn’t find anyone. What could be the matter? I’ve also seen a few cuestions in StackOverflow with a similar issue but it didn’t help.
Вот мой код:
miServlet.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package prueba;
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;
/**
*
* @author 54113
*/
public class miServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet miServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet miServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.setContentType("text/html;charser=UTF-8");
PrintWriter out = response.getWriter();
out.println("Hola");
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
index.jsp:
<%--
Document : index
Created on : 12 dic. 2020, 00:06:47
Author : 54113
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<h4>Haga click <a href="miServlet"> aqui </a> </h4>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<servlet>
<servlet-name>miServlet</servlet-name>
<servlet-class>prueba.miServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>miServlet</servlet-name>
<url-pattern>/miServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path=""/>
Вот сообщения об ошибках:
С Tomcat 7:
(Примечание. Ошибка при создании экземпляра сервлета означает Ошибка при создании экземпляра класса сервлета, а ошибка внутреннего сервера не выполняется. сервер обнаружил внутреннюю ошибку, которая помешала ему выполнить этот запрос. Causa raíz означает «Основная причина»).
Estado HTTP 500 – Internal Server Error
Tipo Informe de Excepción
mensaje Error instanciando clase de servlet [prueba.miServlet]
Descripción El servidor encontró un error interno que hizo que no pudiera rellenar este requerimiento.
excepción
javax.servlet.ServletException: Error instanciando clase de servlet [prueba.miServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2531)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2520)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
causa raíz
java.lang.RuntimeException:
prueba.miServlet.<init>(miServlet.java:1)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2531)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2520)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
nota La traza completa de la causa de este error se encuentra en los archivos de registro del servidor.
Apache Tomcat/7.0.107
С Tomcat 9:
Estado HTTP 500 – Internal Server Error
Tipo Informe de Excepción
mensaje Error instanciando clase de servlet [prueba.miServlet]
Descripción El servidor encontró un error interno que hizo que no pudiera rellenar este requerimiento.
excepción
javax.servlet.ServletException: Error instanciando clase de servlet [prueba.miServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
causa raíz
java.lang.RuntimeException:
prueba.miServlet.<init>(miServlet.java:1)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:832)
nota La traza completa de la causa de este error se encuentra en los archivos de registro del servidor.
Apache Tomcat/9.0.41
Со GlassFish:
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class prueba.miServlet
root cause
com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class prueba.miServlet
root cause
java.lang.RuntimeException:
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 5.0.1 logs.
GlassFish Server Open Source Edition 5.0.1
Finally, here’s the project’s structure:
Большое спасибо!
Лучшее
Leandro
#java #apache #tomcat #web-applications
#java #apache #tomcat #веб-приложения
Вопрос:
MyServlet.java
class MyServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
//private static final long serialVersionUID =102831973239L;
static String task;
public MyServlet(){
}
String tm;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
task = request.getParameter("task");
tm= request.getParameter("reminder_time");
try {
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time=new Date();
formatter.format(time);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection(
"jdbc:mysql://localhost:3306/reminder","sarthak","sar31thak");
String INSERT_RECORD = "insert into ToDo values(?, ?)";
PreparedStatement pstmt = null;
pstmt = con.prepareStatement(INSERT_RECORD);
pstmt.setString(1, task);
pstmt.setDate(2, (java.sql.Date) time);
int rs= pstmt.executeUpdate();
if(rs!=0){
response.sendRedirect("success.html");
return;
}
else{
response.sendRedirect("error.html");
}
con.close();
}
catch(Exception e){
System.out.println("Got an EXCEPTION");}
}
catch (Exception e) {
System.out.println("Got an ERROR");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Alert</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>MyServlet</display-name>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.sar.pkg.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
Что вызывает следующую ошибку
Статус HTTP 500 — Ошибка создания экземпляра класса сервлета com.sar.pkg.MyServlet.MyServlet
введите отчет об исключении
сообщение об ошибке создания экземпляра класса сервлета com.sar.pkg.MyServlet
описание Сервер столкнулся с внутренней ошибкой, которая не позволила ему выполнить этот запрос.
исключение javax.servlet.Исключение ServletException: ошибка создания экземпляра класса сервлета com.sar.pkg.MyServlet org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.Ошибка reportvalve.invoke(ошибка reportvalve.java:100) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java: 408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process (AbstractProtocol.java:603) org.apache.tomcat.util.net .JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker (неизвестный источник) java.util.concurrent.ThreadPoolExecutor$Worker.run (неизвестный источник) java.lang.Thread.run(неизвестный источник)
основная причина java.lang.Исключение IllegalAccessException: класс org.apache.catalina.core.DefaultInstanceManager не может получить доступ к члену класса com.sar.pkg.MyServlet с модификаторами «public» sun.reflect.Reflection.ensureMemberAccess(неизвестный источник) java.lang.Class.newInstance (неизвестный источник) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.Ошибка reportvalve.invoke(ошибка reportvalve.java:100) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java: 408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process (AbstractProtocol.java:603) org.apache.tomcat.util.net .JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker (неизвестный источник) java.util.concurrent.ThreadPoolExecutor$Worker.run (неизвестный источник) java.lang.Thread.run(неизвестный источник)
обратите внимание, что полная трассировка стека основной причины доступна в журналах Apache Tomcat / 7.0.47.
Я попытался устранить эту ошибку, используя другой serialVersionId и очистил проект перед его запуском. Все еще застрял на этом. Пожалуйста, помогите. Заранее спасибо.
Комментарии:
1.Ваш класс должен быть общедоступным.
task
иtm
должны быть локальными переменными, а не переменными-членами: в противном случае ваш сервлет не является потокобезопасным. Вы не защищаете должным образом от отсутствующих или недопустимых параметров.format()
Метод возвращает значение, которое вы отбрасываете.Class.forName()
Строка не требуется с 2007 года. Вы раскрыли свой пароль к базе данных. Во всех случаях происходит утечкаPreparedStatement
и соединения как в случае успеха, так и в случае исключения. Печать вашего собственного сообщения об ошибке вместо исключения недопустима. Ваше форматирование кода отвратительно.2. Можете ли вы мне здесь помочь? Я новичок в Java-кодировании.
3. Я уже сделал это, в мельчайших деталях.
Ответ №1:
Ваш класс сервлета com.sar.pkg.MyServlet
не является общедоступным. Ваше определение
class MyServlet extends HttpServlet{
должно быть
public class MyServlet extends HttpServlet{