我正在运行Tomcat v7.0。我正在努力学习Servlets。我试过使用以下代码:
我试图纠正被叫网址。然后我删除了我的项目并创建了一个新项目。但错误仍然相同," Http 404"。如何使用" Servlet"更正被调用的URL或生成Servlet。接口?Either the called URL is wrong or maybe the code is wrong!
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/Hello2")
public class Hello2 implements Servlet {
ServletConfig config = null;
public Hello2() {
super();
}
@Override
public void destroy() {
System.out.println("Servlet is destroyed!");
}
@Override
public ServletConfig getServletConfig() {
return config;
}
@Override
public String getServletInfo() {
return "Copyright 2017-2018";
}
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
System.out.println("Servlet is initialized!");
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>");
out.println("Hello2");
out.println("</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Hello Hello!!</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
我尝试使用web.xml更改调用URL 这是我的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" 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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SDM</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>
</web-app>
<servlet-mapping>
<servlet-name>Hello2</servlet-name>
<url-pattern>/SDM</url-pattern>
</servlet-mapping>