一、核心接口和类
①Servlet接口
Servlet接口是ServletAPI中最重要的接口,所有Servlet都会直接或间接的与该接口发生联系,或是直接实现该接口,或间接继承自实现了该接口的类。
该接口包含以下五个方法:
init(ServletConfig config)
ServletConfig getServletConfig()
service(ServletRequest req,ServletResponse res)
String getServletInfo()
destroy( )
②GenericServlet抽象类
它对Servlet接口中的部分方法(init和destroy)添加了实现,使得开发时只需要考虑针对service方法的业务实现即可
③HttpServlet类
是继承GenericServlet的基础上进一步的扩展
二Servlet创建的三种方式
①继承HttpServlet
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("我是Servlet创建的第一种方式");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
②实现接口Servlet
public class HelloServlet2 implements Servlet {
@Override
public void destroy() {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
System.out.println("OK");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("我是第二种创建方式");
}
}
③继承·GenericServlet类
public class HelloServlet3 extends GenericServlet{
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
System.out.println("OK");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("我是第三种创建方式");
}
}
三、Servlet的两种配置方式
①注解式配置(Servlet3.0以后才行)
@WebServlet(value = "/hello", loadOnStartup = 1)
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("OK");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
loadOnStartup是设置优先级别,如果有多个Servlet,需要设置,如果只有一个,可以不用设,只有一个可以直接在注解里面写上Servlet名字就行。
②web.xml配置(Servlet所有版本都支持)
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("OK");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
hello2
com.qf.web.servlet.HelloServlet
1
hello2
/hello2.do