1.Servlet是JAVE EE的接口,用于回复客户端的请求
2.使用方式:
- 2.1定义类Servlet实现Servlet接口(不常用)
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class Servlet implements javax.servlet.Servlet
{
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//服务器响应客户端方法
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("服务器被访问,Servlet触发");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
web.xml下声明Servlet程序
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<!--Servlet程序别名 -->
<servlet-name>Servlet</servlet-name>
<!--Servlet程序类 -->
<servlet-class>Servlet</servlet-class>
</servlet>
<!--Servlet程序映射 -->
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<!--/hello 表示访问地址 项目名/hello -->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
- 2.2 定义类Servlet继承HttpServler类(Servler的子类)
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Servlet extends HttpServlet
{
//回复提交方式为GET的方法
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("表单以GET方式提交");
}
//回复提交方式为POST的方法
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("表单以POST方式提交");
}
}
3.Servlet的生命周期
执行Servlet构造方法->执行初始化方法init()->执行service()方法
->执行销毁方法destroy()
Servlet对象是单例
4.ServletConfig类用于读取web.xml中Servlet的配置信息
5.ServletContext类作用:
- 5.1 用于读取web.xml中ServletContext的配置信息
- 5.2 用于获得当前目录的工程路径
System.out.println(context.getContextPath()); //得到工程路径
- 5.3 用于获得项目部署后的绝对路径(如果用idea整合tomcat部署项目,默认部署在IDEA的target路径下,而不是部署在Tomcat路径下)
System.out.println(context.getRealPath("Servlet.java")); //得到工程部署后的Servlet类的绝对路径
- 5.4 用于Map操作
context.setAttribute(key,value)
context.getAttribute(key)