- 三大组件是什么?
1 Servlet
2 Filter
3 Listener
- springboot项目如何注册三个组件
1
@WebServlet("/firstServlet")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(true);
System.out.println(session);
System.out.println("这个是get请求");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("这个是post请求");
}
}
-- 注意启动类上
@SpringBootApplication
@EnableScheduling
@ServletComponentScan
public class SpringbootmybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisApplication.class,args);
}
}
2 创建一个过滤器
@WebFilter(urlPatterns = {"/firstServlet","/html/*"})
public class FirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化....");
}
@Override
public void destroy() {
System.out.println("详情....");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("进入filter...");
HttpServletRequest request = (HttpServletRequest) servletRequest;
String method = request.getMethod();
String contextPath = request.getContextPath();
StringBuffer requestURL = request.getRequestURL();
String remoteAddr = request.getRemoteAddr();
request.setCharacterEncoding("utf-8");
request.setAttribute("请求","参数");
System.out.println("输出信息"+method+contextPath+requestURL+remoteAddr);
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("离开filter...");
}
}
3 创建一个监听器
@WebListener
public class FirstListener implements HttpSessionListener, HttpSessionAttributeListener {
private static int num = 0;
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("打开了一个session");
num++;
System.out.println(num);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("关闭了session");
num--;
System.out.println(num);
}
}