Servlet
1.创建servlet/HelloServlet
package com.cc.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 HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("hello success...");
}
}
知识点:1.Ctrl+O 生成doGet和doPost方法
2. config/MyServletConfig
package com.cc.springboot.config;
import com.cc.springboot.servlet.HelloServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyServletConfig {
// 注册servlet组件
@Bean
public ServletRegistrationBean helloServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new HelloServlet(), "/hello");
// 设置servlet组件的参数,优先级
bean.setLoadOnStartup(1);
return bean;
}
}
知识点:1.ServletRegistrationBean
2.@Configuration和@Bean
3.Ctrl+Alt+V快捷返回值
3.运行项目,浏览器-》localhost:8080/hello
Filter
1.创建filter/MyFilter
package com.cc.springboot.filter;
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
// 初始化
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter初始化操作");
}
@Override
// 销毁
public void destroy() {
System.out.println("filter销毁");
}
@Override
// 过滤
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("myfilter过滤 完成");
// 放行请求
chain.doFilter(request,response);
}
}
2.配置到config
// 注册filter组件
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
// 设置自定义filter
bean.setFilter(new MyFilter());
// 过滤哪些请求
bean.setUrlPatterns(Arrays.asList("/hello"));
return bean;
}
Listener
1.创建 listener/MyListener
package com.cc.servlet.listener;
import javax.servlet.*;
//监听应用启动与销毁
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("SpringBoot.Servlet应用启动");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("SpringBoot.Servlet应用销毁");
}
}
2.配置到config
// 注册监听器
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new MyListener());
return bean;
}