一个简单的servlet项目结构
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"
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>HelloServlet</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.qf.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
servlet相关代码
package com.qf.servlet; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class HelloServlet implements Servlet { @Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { System.out.println("helloServlet"); } @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub } @Override public ServletConfig getServletConfig() { // TODO Auto-generated method stub return null; } @Override public String getServletInfo() { // TODO Auto-generated method stub return null; } @Override public void destroy() { // TODO Auto-generated method stub } }
url:http://localhost:8080/HelloServlet/hello
控制台输出结果:
helloServlet
具体执行过程:
- 找到tomcat应用
- 找到项目
- 找到web.xml,在web.xml中找到url-pattern标签的内容能匹配/hello的
- 找到这个url-pattern对应的servlet-name,进而找到相关servlet-class
- 创建该servlet-class对应的servlet类的实例
- 调用service方法进行处理