我有以下 servlet 代码
public void doPost(HttpServletRequest request, HttpServletResponse response){
Backup bup = new Backup();
bup.doBackup();
response.setContentType("text/html");
PrintWriter out;
try {
out = response.getWriter();
out.println("You backed up your data - well hopefully");
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
以及以下堆栈跟踪
javax.servlet.ServletException:类 view.BackupServlet 不是 Servlet 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:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619)
根本原因
java.lang.ClassCastException: view.BackupServlet 无法转换为 javax.servlet.Servlet 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:849) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) java.lang.Thread.run(Thread.java:619)
web.xml 是
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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-<br>app_2_4.xsd">
<display-name>Backup</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>BackupServlet</description>
<display-name>BackupServlet</display-name>
<servlet-name>BackupServlet</servlet-name><br>
<servlet-class>view.BackupServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BackupServlet</servlet-name>
<url-pattern>/BackupServlet</url-pattern>
</servlet-mapping>
</web-app>`
您还没有显示您的类声明 - 我的猜测是您的类没有扩展
Servlet
或 HttpServlet
。
如果是这样,则检查您的部署中有多少个不同的 servlet.jar 文件 - 可能是它由两个不同的类加载器加载。
doPost
的类必须扩展
javax.servlet.Servlet
,但最好是
javax.servlet.HttpServlet
public class BackupServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) {
.
.
.
}
}
pom.xml
中获得了正确的范围:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
provided 将使 javax.servlet 在运行时由容器提供。