转自:https://www.jianshu.com/p/6830989985e9
1.注册Servlet
配置类:
@Configuration
public class MyServerConfig {
// 注册三大组件
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean servletregistrationbean = new ServletRegistrationBean(new MyServlet() ,"/myservlet"){
};
return servletregistrationbean;
}
// 配置嵌入式Servlet容器
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> myembeddedServletContainerCustomizer(){
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>(){
// 定制嵌入式Servlet容器相关规则
@Override
public void customize(ConfigurableWebServerFactory factory) {
factory.setPort(8081);
}
};
}
}
自定义的Servlet类
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 {
doPost(req, resp);
}
/**
* 处理post请求
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("hello");
}
}
然后在浏览器访问http://localhost:8081/myservlet
2.注册Filter
// 注册filter
@Bean
public FilterRegistrationBean myfilter(){
FilterRegistrationBean filterregistrationbean = new FilterRegistrationBean();
filterregistrationbean.setFilter(new MyFilter());
filterregistrationbean.setUrlPatterns(Arrays.asList("/hello","/myservlet"));
return filterregistrationbean;
}
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("myfilter");
filterChain.doFilter(servletRequest,servletResponse);
}
然后访问"/myservlet"或者"/hello"控制台都会打印myfilter
3.注册Listener(这里以ServletContextListener为例)
// 注册Listener
@Bean
public ServletListenerRegistrationBean mylistener(){
ServletListenerRegistrationBean servletListener = new ServletListenerRegistrationBean<MyListener>(new MyListener());
return servletListener;
}
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("web项目生成");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("web项目销毁");
}
}
然后启动项目
作者:二营长家的张大炮
链接:https://www.jianshu.com/p/6830989985e9
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。