介绍:
Servlet就是一个特殊的类,可以和页面进行交互的。Servlet和Filter 还有Listener 并成为Javaweb 三大组件。
如果让我们的类变成servlet类:
1.实现javax.servlet.Servlet接口。(了解)
package com.chinasofti.servlet;
import javax.jws.WebService;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
/**
-
Created by 86158 on 2021/7/19.
/
@WebServlet("/one")
public class OneServlet implements Servlet{
/**- 初始化方法
- @param servletConfig
- @throws ServletException
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println(“初始化”);
}
/***
- 获取servlet配置相关的方法
- @return
*/
@Override
public ServletConfig getServletConfig() {
System.out.println(“配置相关”);
return null;
}
/***
- 具体servlet类执行的方法
- @param servletRequest
- @param servletResponse
- @throws ServletException
- @throws IOException
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println(“service方法”);
}
/****
- 或者整个web项目servlet 相关的配置相关的方法
- @return
*/
@Override
public String getServletInfo() {
System.out.println(“info配置”);
return null;
}
/***
- 销毁方法
*/
@Override
public void destroy() {
System.out.println(“销毁”);
}
}
注意: init是servlet初始化方法,service方法执行之前执行的,执行完init方法之后,然后在执行service方法。Destory方法是我们web服务器关闭之前执行的。
2.继承javax.servlet.GenericServlet类(了解)
package com.chinasofti.servlet;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
/**
- Created by 86158 on 2021/7/19.
*/
@WebServlet("/two")
public class TwoServlet extends GenericServlet{
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println(“tow servlet被执行”);
}
}
3.继承javax.servlet.http.HttpServlet类(掌握)
package com.chinasofti.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
-
Created by 86158 on 2021/7/19.
/
@WebServlet("/three")
public class ThreeServlet extends HttpServlet {
/***- doGet是用来接收用户的get请求
- @param req
- @param resp
- @throws ServletException
- @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(“get方法被调用”);
}
/***
- 用来接收用户的post请求
- @param req
- @param resp
- @throws ServletException
- @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(“post方法被调用”);
}
}