Servlet API 概览
-
Servlet 有4个java包:
- javax.servlet,Servlet 和Servlet容器之间契约的类和接口
- javax.servlet.http,HTTP Servlet和Servlet容器之间契约的类和接口
- javax.servlet.annotation
- javax.servlet.descriptor
javax.servlet 中的主要类型:
Servlet 技术核心是Servlet,它是所有Servlet类必须直接或间接实现的一个接口。
Servlet接口定义了Servlet与Servlet容器之间的契约:
Servlet 接口
-
5个方法
- void init(ServletConfig config) throws ServletException
- void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
- void destroy()
- java.lang.String getServletInfo()
- ServletConfig getServletConfig()
init : 该Servlet第一次被请求时,Servlet容器会调用这个方法,且这个方法之后不会再调用。调用这个方法时,Servlet容器会传入一个ServletConfig,init()中一般会将ServletConfig赋给一个类级变量
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
}
service:每次请求Servlet时,Servlet容器就会调用这个方法
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{
String servletName = servletConfig.getServletName();
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.print("<html><head></head>" + "<body>Hello from " + servletName + "</body></html>");
}
destroy:销毁Servlet时调用
getServletInfo:
getServletConfig:
编写、编译第一个Servlet类
Servlet类的名称要以Servlet为后缀
package com.wyx.servlet;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "MyServlet", urlPatterns = { "/my" })
public class MyServlet implements Servlet {
private transient ServletConfig servletConfig;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
}
@Override
public ServletConfig getServletConfig(){
return servletConfig;
}
@Override
public String getServletInfo(){
return "My Servlet";
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{
String servletName = servletConfig.getServletName();
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.print("<html><head></head>" + "<body>Hello from " + servletName + "</body></html>");
}
@Override
public void destroy(){
}
}
@WebServlet(name = “MyServlet”, urlPatterns = { “/my” })
声明一个Servlet,并且url为 /my 样式时要调用此Servlet
运行结果:
next :HttpServlet please waiting…