---在WEB-INF/classes新建类MyServlet.java,内容如下:
package com.king;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet implements Servlet {
public void init(ServletConfig config) throws ServletException {
System.out.println("MyServlet init -------");
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("MyServlet service -------");
}
public void destroy() {
System.out.println("MyServlet destroy -------");
}
public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
}
然后直接编译:
javac -d . MyServlet.java -classpath /home/king/xxx/servlet-api.jar
如果已经在CLASSPATH设置servlet-api.jar, 则后面不用带-classpath
编译成功会生成 com/king/MyServlet.class
---然后在web.xml内配置该Servlet,内容如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
version="3.0"
metadata-complete="true">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.king.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
---重启tomcat, 在浏览器访问:http://localhost:8080/MyApp/MyServlet
观察后台打印信息.
ps: linux下可以这样看log
1、先切换到:cd tomcat/logs
2、tail -f catalina.out
3、这样运行时就可以实时查看运行日志了