三个注解都必须在启动类增加@ServletComponentScan
才能够被扫描到。
@WebServlet
可用于根据不同条件,重定向请求至不同URL。
示例代码
@WebServlet(name = "/my")
@Slf4j
public class MyWebServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
log.info("进入get方法");
log.info(req.getParameter("name"));
doPost(req,resp);
}
@Override
protected void doHead(HttpServletRequest req, HttpServletResponse resp) {
log.info("进入get方法");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
log.info("进入post方法");
log.info(req.getParameter("name"));
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
log.info("进入put方法");
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
log.info("进入delete方法");
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
log.info("进入option方法");
}
@Override
public void destroy() {
log.info("servlet>>>destroy");
}
@Override
public void init() {
log.info("servlet>>>init");
}
}
使用postman分别通过get
、post
、delete
等进行请求http://localhost:8080/my?name=张三
,可以查看输出结果
@WebFilter
可用于拦截/过滤请求,提前对请求的request
进行判断处理,在doFilter
后过滤器放行,调用实际请求URL路径。
示例代码
@WebFilter("/my")
@Slf4j
public class MyWebFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("filter>>>init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("进入doFilter方法");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
log.info("filter>>>destroy");
}
}
再次请求,查看输出结果
[alt type="error"]注意看输出顺序[/alt]
@WebListener
在spring启动之前监听执行初始化操作,可用于提前加载缓存等。
@WebListener
@Slf4j
public class MyWebListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
log.info("requestDestroyed");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
log.info("requestInitialized");
}
}
输出结果
评论 (0)