package com.study.servlet;/*
@author Tmac
@version 1.0
*/
import javax.servlet.*;
import java.io.IOException;
public class StudyServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init() 方法被调用");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("Service方法被调用");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
<servlet>
<servlet-name>StudyServlet</servlet-name>
<servlet-class>com.study.servlet.StudyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudyServlet</servlet-name>
<url-pattern>/study</url-pattern>
</servlet-mapping>
#servlet标签给Tomcat配置Servlet程序
#servlet-name标签是给Servlet程序起一个名字
#servlet-class是Servlet程序全类名
#servlet-mapping标签是给Servlet程序配置访问地址
Servlet 容器(比如: Tomcat)加载 Servlet,加载完成后,Servlet 容器会创建一个 Servlet 实例 并调用 init()方法,init()方法只会调用一次, Servlet 容器在下面的情况装载 Servlet:
public void service(ServletRequest servletRequest,
ServletResponse servletResponse) throws ServletException,
IOException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String method = httpServletRequest.getMethod();
if("GET".equals(method)) {
doGet(); //用 doGet() 处理 GET 请求
} else if("POST".equals(method)) {
doPost(); //用 doPost() 处理 POST 请求
}
}
public void doGet() {
System.out.println("doGet() 被调用..");
}
public void doPost() {
System.out.println("doPost() 被调用..");
}