先编写三大组件
MyServlet:
public class MyServlet extends HttpServlet {
/**
* 处理get请求
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("MyServlet 被调用");
resp.getWriter().write("Hello MyServlet");
}
/**
* 处理post请求
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("MyServlet 被调用");
resp.getWriter().write("Hello MyServlet");
}
}
MyFilter:
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("MyFilter 被调用");
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
MyListener:
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized...web应用启动");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed...当前web项目销毁");
}
进行相应的配置
servlet要添加进容器需要以ServletRegistrationBean的形式,fliter要添加进容器需要以FilterRegistrationBean的形式,Listener添加进容器需要以ServletListenerRegistrationBean的形式
* 配置三大组件
*
* @author zhouning
*/
@Configuration
public class MyServerConfig {
@Bean
public ServletRegistrationBean myServlet(){
//和 “/myServlet”想映射
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
registrationBean.setLoadOnStartup(1);
return registrationBean;
}
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
//对于 “/hello”,“/myServlet”进行拦截
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
@Bean
public ServletListenerRegistrationBean myListener(){
//
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
转自:https://blog.csdn.net/qq_41474648/article/details/106147401