Servlet: 请求处理的鼻祖,不过现在基本废弃。
Filter:对一切请求均有效,可以实现敏感词过滤,请求响应的修改等等。
Listener: 对事件的监听,以ServletContentListener, SessionListener为主
Servlet的使用(不推荐使用)
使用@WebServlet注解声明,使用@ServletComponentScan开启扫描
? ? ? ? ?a. 使用@WebServlet注解声明
@WebServlet(name = "myServlet", urlPatterns = {"/test/mytest"})
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("[MyServlet] doGet");
resp.setContentType("application/json");
resp.setStatus(200);
PrintWriter writer = resp.getWriter();
writer.write("{\"data\": 100}");
writer.flush();
}
}
????????b. 注解扫描
Filter的使用?
实现Filter接口的doFilter方法,使用@WebFilter进行注解, 开启ServletComponentScan
????????a.?实现Filter接口的doFilter方法,使用@WebFilter进行注解
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("[MyFilter] filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("[MyFilter] do filter");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("[MyFilter] filter destroy");
}
}
????????b.开启ServletComponentScan
?
Listener的使用
使用@WebListener注解标记,同时实现ServletContextListener、HttpSessionListener接口
@WebListener
public class MyContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("[MyContextListener] context created");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("[MyContextListener] context destroyed");
}
}
@WebListener
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("[MySessionListener] session created");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("[MySessionListener] session destroyed");
}
}
?开启ServletComponentScan
|