问题:使用注解方式访问servlet,并且已经修改完所有注意的地方。
如:
@WebServlet(description = “使用eclipse快速访问servlet”, urlPatterns = { “/WelcomeServlet2” })
metadata-complete=“false“ version=“4.0“
但还是报错。
WelcomeServlet2类:
代码如下:
package test_servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class WelcomeServlet2
*/
@WebServlet(description = "使用eclipse快速访问servlet", urlPatterns = { "/WelcomeServlet2" })
public class WelcomeServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("WelcomeServlet2访问成功");
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
metadata-complete="false" version="4.0">
<display-name>Servlet50Project</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>
<servlet-name>a</servlet-name>
<servlet-class>test_servlet.WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
</web-app>
index.jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="WelcomeServlet">WelcomeServlet</a>
<a href="WelcomeServlet2">WelcomeServlet2</a>
</body>
</html>
解决方案:经过反复debug式修改,发现是在import时导包出现错误。
由于本人安装了最新版的Tomcat服务器,即apache Tomcat v10.0,里面的servlet是5.0版本,发现里面的包名发生了变化,包名由javax.servlet变成了jakarta.servlet,而eclipse新建JSP文件,默认的包名的路径为javax.servlet,许多操作都是基于该包之下。所以本人下载一个javax.servlet-api-4.0.1.jar包,并导入到项目中。
结果由于该包支持servlet是4.0版本的,无法兼容servlet5.0最新版,导致404错误。解决办法是将eclipse默认的包名的路径javax.servlet改为jakarta.servlet,便可解决问题。
修改后运如图:表示访问成功。