实现doPost,doGet请求
package cn.kitey.springboot.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//调用doPost请求
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("Hello Servlet!");
}
}
/**
* 注册Servlet
* @return
*/
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
return servletRegistrationBean;
}
实现doFilter方法
package cn.kitey.springboot.filter;
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("MyFilter process");
//放行
filterChain.doFilter(servletRequest,servletResponse);
}
}
我这里拦截是/MyServlet,如果成功,控制台将进行打印
/**
* 注册filter
* @return
*/
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
//设置拦截器
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/myServlet"));
return registrationBean;
}
监听web应用的创建和销毁
package cn.kitey.springboot.listener;
import javax.servlet.Servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* 配置listener监听器
*/
public class MyListener implements ServletContextListener{
/**
* wb应用启动
* @param sce
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized。。。。当前web应用启动!");
}
/**
* web应用销毁
* @param sce
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed。。。。当前web应用销毁!");
}
}
/**
* 注册监听器
* @return
*/
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}