1.springboot与servlet的整合
(1)注意,servlet一定要在启动类的包下或者所在包的子包下,才能被扫描到。
servlet类,name是本类的名字,urlpattents是url栏上的地址。
@WebServlet(name = "FirstServlet",urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("我是你写的第一个sprubgboot与servlet的整合");
}
}
在启动类只需要添加@ServletComponentScan注解即可
(2)添加bean的形式不使用@ServletComponentScan注解通过添加@bean的形式
@Bean
public ServletRegistrationBean getit(){
ServletRegistrationBean servletRegistrationBean=new ServletRegistrationBean(new FirstServlet());
servletRegistrationBean.addUrlMappings("/first");
return servletRegistrationBean;
}
2.springboot与filter的整合,与servlet整合相似,启动类不会变,只需要,编写自己的filter类即可
@WebFilter(filterName="FirstFileter",urlPatterns = "/firstFilter")
public class FirstFileter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.setContentType("text/html;charset=utf-8");
servletResponse.getWriter().write("filter");
}
@Override
public void destroy() {
}
}
3.整合监听器:
@WebListener
public class FirstListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("listener init--------");
}
}








网友评论