Есть некий сервлет
package com.example.DBProject;
import java.io.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<h1> first servlet</h1>");
out.println("</html>");
}
}
И web.xml
<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">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.DBProject.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
При запуске сервера и переходе по ссылке к /hello (http://localhost:8080/hello) появляется ошибка
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Ошибка создания экземпляра класса сервлета [com.example.DBProject.HelloServlet]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
jakarta.servlet.ServletException: Ошибка создания экземпляра класса сервлета [com.example.DBProject.HelloServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
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:353)
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:870)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
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)
Root Cause
java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet
java.base/java.lang.ClassLoader.defineClass1(Native Method)
java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2470)
org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:866)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1370)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
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:353)
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:870)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
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)
Root Cause
java.lang.ClassNotFoundException: javax.servlet.http.HttpServlet
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1401)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224)
java.base/java.lang.ClassLoader.defineClass1(Native Method)
java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2470)
org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:866)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1370)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
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:353)
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:870)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
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)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/10.0.5
Структура проекта, если это играет роль
P.S. В pom.xml нужные dependencies есть
I just started learning Hibernate and Servlets.
I have a form (name, email), I fill that fields and the request goes to the server.
Then I fetch the data from server and print them.
This WORKS CORRECTLY!
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("userName");
String email = request.getParameter("email");
String ip = request.getRemoteAddr();
response.getWriter().println("<html>");
response.getWriter().println("<head>");
response.getWriter().println("<title>This is a response</title>");
response.getWriter().println("<head>");
response.getWriter().println("<body>");
response.getWriter().println("<br>Your name is: " + name);
response.getWriter().println("<br>Your email is: " + email);
response.getWriter().println("<br>Your IP address is: " + ip);
response.getWriter().println("</body>");
response.getWriter().println("</html>");
}
Also I have a DB (db and .xml files are properly configured, ping is succesful, mapping is written) and Hibernate code:
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.configure("hibernate.cfg.xml");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Data data = new Data();
data.setUserName(name);
data.setUserEmail(email);
session.save(data);
session.getTransaction().commit();
session.close();
}
Also I have a Data class:
@Entity
public class Data {
@Id
@GeneratedValue
private int Id;
private String userName;
private String userEmail;
//getteres, setters...
}
But if I put this code into the Servlet, I get an HTTP error 500. The error message as I can determine it is this:
javax.servlet.ServletException: Error instantiating servlet class org.server.db.test.ServletExample org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:722)
How can I put my info from the server to the database?
my web.xml file:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>Example02</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>ServletExample</display-name>
<servlet-name>ServletExample</servlet-name>
<servlet-class>org.server.db.test.ServletExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletExample</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
hibernate cfg file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/db</property>
<property name="connection.username">postgres</property>
<property name="connection.password">***</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">2</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Enable Hibernate's current session context -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="org.server.db.test.Data" />
<mapping class="org.server.db.test.ServletExample" />
</session-factory>
</hibernate-configuration>
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 #xml #servlets
Вопрос:
То, что я пытаюсь сделать, — это создать простое веб-приложение, в котором учитель может записывать оценки учащихся из файлов Excel в базу данных
Я пытался очистить и перестроить проект, очистить рабочий путь tomcat, но, похоже, ничего не получилось
Вот мой код сервлета, который вызывает ошибку
@WebServlet(name = "NhapFileExcelServlet", urlPatterns = {"/nhapFileExcelServlet"})
public class NhapFileExcelServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* 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, ParseException {
Part filePart = request.getPart("excel");
InputStream inputStream = filePart.getInputStream();
String fileName = filePart.getSubmittedFileName();
if(fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
// Lấy file excel upload về server
String uploadFileDirectory = "\Users\thanhhieu\Desktop\test" fileName;
File fileToSave = new File(uploadFileDirectory);
Files.copy(inputStream, fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING);
request.setAttribute("isValid", Boolean.TRUE);
ExcelController excelController = new ExcelController(uploadFileDirectory);
excelController.readExcel();
ArrayList<SinhVien> dsSinhVien = excelController.getDsSinhVien();
ArrayList<Diem> dsDiem = excelController.getDsDiem();
request.setAttribute("dsSinhVien", dsSinhVien);
request.setAttribute("dsDiem", dsDiem);
}
else {
request.setAttribute("isValid", Boolean.FALSE);
}
//Chuyển request và response sang GDdiem.jsp
String url = "/GDdiem.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
System.out.println("Ma lop gui sang servlet: " request.getParameter("maLop"));
dispatcher.forward(request, response);
}
// <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, FileNotFoundException {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(NhapFileExcelServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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, FileNotFoundException {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(NhapFileExcelServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Та часть, которая будет вызывать сервлет
<div style = "margin: auto">
<form action="nhapFileExcelServlet" method = "post" enctype="multipart/form-data">
<input type="hidden" id="lopID" name="maLop" value= <%= maLop %> />
<input type="hidden" id="monID" name="maMon" value= <%= maMon %> />
<label for="fileID">Chọn file Excel danh sách điểm:</label>
<input type="file" id="fileID" accept=".xls, .xlsx" name="excel"><br>
<button type="submit">Nhập</button>
</form>
</div>
Мой xml-файл
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
<servlet>
<servlet-name>NhapFileExcelServlet</servlet-name>
<servlet-class>servlet.NhapFileExcelServlet</servlet-class>
<multipart-config/>
</servlet>
<servlet>
<servlet-name>TinhDiemServlet</servlet-name>
<servlet-class>servlet.TinhDiemServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LuuDiemLopServlet</servlet-name>
<servlet-class>servlet.LuuDiemLopServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NhapFileExcelServlet</servlet-name>
<url-pattern>/nhapFileExcelServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>TinhDiemServlet</servlet-name>
<url-pattern>/tinhDiemServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LuuDiemLopServlet</servlet-name>
<url-pattern>/luuDiemLopServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>
И структура моего проекта
Это трассировка стека
jakarta.servlet.ServletException: Error instantiating servlet class [servlet.NhapFileExcelServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
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:353)
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:870)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:835)
cause mère
java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet
java.base/java.lang.ClassLoader.defineClass1(Native Method)
java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2470)
org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:866)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1370)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
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:353)
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:870)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:835)
cause mère
java.lang.ClassNotFoundException: javax.servlet.http.HttpServlet
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1401)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224)
java.base/java.lang.ClassLoader.defineClass1(Native Method)
java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2470)
org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:866)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1370)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
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:353)
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:870)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:835)
Любой совет приветствуется
Комментарии:
1. Приложение пытается использовать класс javax.servlet.http. HttpServlet, но он не может его найти. Этот класс можно найти в servlet-api-x.x.jar. Попробуйте добавить эту банку в свой путь к классу.
2. Я не знаю, правильно ли я это сделал, но я добавил это в зависимости от своего проекта и все еще не работает
Ответ №1:
NVM У меня все получилось
Оказывается, мне нужно не только импортировать файлы jar, но и указать зависимость в pom.xml потому что IDE не делает это автоматически
Комментарии:
1. да, это подразумевается, если вы используете инструменты сборки maven или gradle.
Solution 1:[1]
When I place the .class file in the corresponding Tomcat directory, start the server and try to interact with the app, I get the following exception:
java.lang.ClassNotFoundException: javax.servlet.http.HttpServlet
I tried placing the javax.servlet-api-4.0.1 in the Tomcat/lib directory, but then I get:
java.lang.ClassCastException: class com.example.controllers.BeerSelect cannot be cast to class jakarta.servlet.Servlet
The jakarta.servlet.Servlet
is part of Servlet API version 5.0 which in turn is part of Jakarta EE version 9. Your servlet is actually extending from javax.servlet.Servlet
which in turn is part of an older JEE version which is actually not supported by your target runtime (Tomcat 10.x).
You have 2 options:
-
Replace the
javax.servlet.*
imports in your code byjakarta.servlet.*
ones.import jakarta.servlet.*; import jakarta.servlet.http.*;
Then you can just compile against the libraries from a Servlet 5.0 based target runtime.
-
Or, downgrade the servlet container from Servlet API version 5.0 to a previous version, at least the one still having the
javax.servlet.*
package name. Tomcat 9.x is the latest one still having the old package.
The technical reason is that during the step from Java/Jakarta EE 8 to Jakarta EE 9 all javax.*
packages have been renamed to jakarta.*
packages. So there is no backwards compatibility anymore since Jakarta EE 9.
So, when following any servlet tutorials which still use the old javax.servlet.*
package while you’re using Tomcat 10 or newer, then you need to manually swap out the package used in code examples for the jakarta.servlet.*
one. Generally it’ll work just fine.
See also:
- Apache Tomcat — versions
- Tomcat casting servlets to javax.servlet.Servlet instead of jakarta.servlet.http.HttpServlet (this answer contains complete examples of proper
pom.xml
declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8-, just in case you’re using Maven).
Solution 2:[2]
I have tested the and managed to compile the java file on Apache Tomcat 9.0.39.
At this point in time, Apache Tomcat 10 is in development and there is no stable version:
http://tomcat.apache.org/whichversion.html
Downgrading your Apache Tomcat version should fix the problem.
Solution 3:[3]
Sree Kumar wrote this comment on another duplicate question which solved the problem for me:
Right-click on project -> Build Path -> Configure Build Path… -> Libraries (tab) -> Select Classpath -> Add Library -> Server Runtime -> Select the one you must have added for Tomcat 10.