1.Web组件
Servlet
Filter
Listener
项目目录结构:
自定义的servlet、filter、listener的注册器:
2.1 自定义的servlet UserServlet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package com.example.demo.servlet;import java.io.IOException;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L ; @Override public void init (ServletConfig config) throws ServletException { super .init(config); String env = config.getInitParameter("env" ); String dataSource = config.getInitParameter("dataSource" ); System.out.println("servlet env = " + env); System.out.println("servlet dataSource = " + dataSource); } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost()" ); } }
2.2 自定义的Filter MyFilter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.example.demo.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class MyFilter implements Filter { @Override public void init (FilterConfig filterConfig) throws ServletException { String env = filterConfig.getInitParameter("env" ); String dataSource = filterConfig.getInitParameter("dataSource" ); System.out.println("filter env = " + env); System.out.println("filter dataSource = " + dataSource); } @Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("doFilter()" ); chain.doFilter(request, response); } }
2.3 自定义的Listener MyListener
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.example.demo.listener;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class MyListener implements ServletContextListener { @Override public void contextInitialized (ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext(); servletContext.setAttribute("contextPath" , servletContext.getContextPath()); System.out.println("MyListener contextInitialized" ); } @Override public void contextDestroyed (ServletContextEvent sce) { ServletContextListener.super .contextDestroyed(sce); } }
3. Config WebObjectConfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 package com.example.demo.config;import java.util.ArrayList;import java.util.Collection;import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.example.demo.filter.MyFilter;import com.example.demo.listener.MyListener;import com.example.demo.servlet.UserServlet;@Configuration @ConfigurationProperties(prefix = "myweb") public class WebObjectConfig { private static final String USER_SERVLET_NAME = "userServlet" ; private String[] servletUrl; public String[] getServletUrl() { return servletUrl; } public void setServletUrl (String[] servletUrl) { this .servletUrl = servletUrl; } @Bean(USER_SERVLET_NAME) public UserServlet getUserServlet () { return new UserServlet (); } @Bean @ConditionalOnBean(value = UserServlet.class, name = USER_SERVLET_NAME) public ServletRegistrationBean<UserServlet> servletRegistrationBeanUserServlet (UserServlet userServlet) { ServletRegistrationBean<UserServlet> servletRegistrationBean = new ServletRegistrationBean <>(); servletRegistrationBean.setServlet(userServlet); servletRegistrationBean.addUrlMappings(servletUrl); servletRegistrationBean.addInitParameter("env" , "test" ); servletRegistrationBean.addInitParameter("dataSource" , "mysql" ); servletRegistrationBean.setLoadOnStartup(1 ); return servletRegistrationBean; } private static final String MYFILE_NAME = "myFilter" ; @Bean(name = MYFILE_NAME) public MyFilter myFilter () { return new MyFilter (); } @Bean @ConditionalOnBean(name = MYFILE_NAME, value = MyFilter.class) public FilterRegistrationBean<MyFilter> filterRegistrationBeanMyFilter (MyFilter myFilter) { FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean <>(); filterRegistrationBean.setFilter(myFilter); Collection<String> urlPatterns = new ArrayList <>(); urlPatterns.add("/*" ); filterRegistrationBean.setUrlPatterns(urlPatterns); filterRegistrationBean.addInitParameter("env" , "prd" ); filterRegistrationBean.addInitParameter("dataSource" , "oracle" ); return filterRegistrationBean; } @Bean public MyListener myListener () { return new MyListener (); } @Bean public ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBeanMyListener (MyListener myListener) { ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean <>(); servletListenerRegistrationBean.setListener(myListener); return servletListenerRegistrationBean; } }
4. application.yml 1 2 3 4 5 6 myweb: servlet-url: - /user.do - /user.test
5. 启动类 1 2 3 4 5 6 7 8 9 10 11 12 13 package com.example.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class Application { public static void main (String[] args) { SpringApplication.run(Application.class, args); } }
运行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.4.5) 2022-06-02 21:41:18.370 INFO 15132 --- [ restartedMain] com.example.demo.Application : Starting Application using Java 1.8.0_271 on DESKTOP-IOB28AF with PID 15132 (E:\SpringToolSuite\project\demo-4.8.1\10_springboot_web_3components\target\classes started by Tom in E:\SpringToolSuite\project\demo-4.8.1\10_springboot_web_3components) 2022-06-02 21:41:18.373 INFO 15132 --- [ restartedMain] com.example.demo.Application : No active profile set, falling back to default profiles: default 2022-06-02 21:41:18.411 INFO 15132 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2022-06-02 21:41:18.411 INFO 15132 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2022-06-02 21:41:19.292 INFO 15132 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-06-02 21:41:19.301 INFO 15132 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-06-02 21:41:19.302 INFO 15132 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.45] 2022-06-02 21:41:19.343 INFO 15132 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-06-02 21:41:19.343 INFO 15132 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 932 ms MyListener contextInitialized filter env = prd filter dataSource = oracle 2022-06-02 21:41:19.502 INFO 15132 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2022-06-02 21:41:19.645 INFO 15132 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 servlet env = test servlet dataSource = mysql 2022-06-02 21:41:19.671 INFO 15132 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2022-06-02 21:41:19.681 INFO 15132 --- [ restartedMain] com.example.demo.Application : Started Application in 1.642 seconds (JVM running for 2.035)
浏览器访问: http://localhost:8080/user.do
或http://localhost:8080/user.test
扩展 1.Servlet的注册
(1) Java2EE方法
web.xml
1 2 3 4 5 6 7 8 <servlet > <servlet-name > userServlet</servlet-name > <servlet-class > com.sxt.servlet.UserServlet</servlet-class > </servlet > <servlet-mapping > <servlet-name > userServlet</servlet-name > <url-patten > /user.do</url-patten > </servlet-mapping >
(2) 注解的方式
2.Filter的注册
(1) Java2EE方法
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 <filter > <filter-name > </filter-name > <filter-class > </filter-class > </filter > <filter-mapping > <filter-name > </filter-nane > </filter-mapping >
(2) 注解的方式
3.Listener的注册
(1) Java2EE方法
web.xml
1 2 3 <listener > <listener-class > org.springframework.web.context.ContextLoaderListener</listener-class > </listener >
(2) 注解的方式
监听的内容:
1 2 3 4 5 6 ServletContext |--ServletContextListener ServletContextAttributeListener HttpSession |--HttpSessionListener HttpSessionAttributeListener ServletRequet |-- ServletRequestListener ServletRequestAttributeListener