詳解IDEA中SpringBoot整合Servlet三大組件的過程
Spring MVC整合
SpringBoot提供為整合MVC框架提供的功能特性
- 內(nèi)置兩個視圖解析器:ContentNegotiatingViewResolver和BeanNameViewResolver
- 支持靜態(tài)資源以及WebJars
- 自動注冊了轉(zhuǎn)換器和格式化器
- 支持Http消息轉(zhuǎn)換器
- 自動注冊了消息代碼解析器
- 支持靜態(tài)項目首頁index.html
- 支持定制應(yīng)用圖標(biāo)favicon.ico
- 自動初始化Web數(shù)據(jù)綁定器:ConfigurableWebBindingInitializer
Spring MVC功能擴(kuò)展實現(xiàn)
- 項目環(huán)境搭建(結(jié)構(gòu)如這篇博客)
- 功能擴(kuò)展實現(xiàn)
- 注冊視圖管理器
/* 在config文件夾下編寫配置類 實現(xiàn)WebMvcConfigurer接口,擴(kuò)展MVC功能 測試前將LoginController控制類注釋,更好的觀察效果 */ @Configuration public class MyMVCConfig implements WebMvcConfigurer { //添加視圖管理 @Override public void addViewControllers(ViewControllerRegistry registry) { // 請求toLoginPage映射路徑或者login.html頁面都會自動映射到login.html頁面 registry.addViewController("/toLoginPage").setViewName("login"); registry.addViewController("/login.html").setViewName("login"); } }
- 測試后發(fā)現(xiàn),使用這種方式無法獲取后臺處理的數(shù)據(jù),比如登錄頁面中的年份。
- 使用WebMvcConfigurer接口中的addViewControllers(ViewControllerRegistry registry)方法定制
視圖控制,只適合較為簡單的無參數(shù)視圖Get方式的請求跳轉(zhuǎn),對于有參數(shù)或需要業(yè)務(wù)處理的跳轉(zhuǎn)請求,最好還是采用傳統(tǒng)方式處理請求。
注冊自定義攔截器
/* 自定義一個攔截器類,實現(xiàn)簡單的攔截業(yè)務(wù) */ @Configuration public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 用戶請求/admin開頭路徑時,判斷用戶是否登錄 String uri = request.getRequestURI(); Object loginUser = request.getSession().getAttribute("loginUser"); if(uri.startsWith("/admin")&&null==loginUser){ response.sendRedirect("/toLoginPage"); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable ModelAndView modelAndView) throws Exception { //向request域中存放當(dāng)前年份用于頁面動態(tài)展示 request.setAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR)); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
- 自定義攔截器類MyInterceptor實現(xiàn)了HandlerInterceptor接口。在preHandle()方法中,如果用戶請求以“/admin”開頭,
則判斷用戶是否登錄,如果沒有登錄,則重定向到“/toLoginPage”請求對應(yīng)的登錄頁面。
- 在postHandle()方法中,使用request對象向前端頁面?zhèn)鬟f表示年份的currentYear數(shù)據(jù)。
- 在自定義配置類MyMVCConfig中,重寫addInterceptors()方法注冊自定義的攔截器,如下
@Autowired private MyInterceptor myInterceptor; //添加攔截器管理 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor) .addPathPatterns("/**") .excludePathPatterns("/login.html"); }
- 使用@Autowired注解引入自定義的MyInterceptor攔截器組件,重寫其中addInterceptors()方法注冊自定義的攔截器
- 使用addPathPatterns("/**")方法攔截所有路徑請求,excludePathPatterns("/login.html")方法對“l(fā)ogin.html”路徑請求放行處理。
- 項目重啟后,訪問localhost:8080/admin,跳轉(zhuǎn)到登錄界面,自定義攔截器生效。
Spring Boot 整合Servlet三大組件
組件注冊方式整合Servlet三大組件
在Spring Boot中,使用組件注冊方式整合內(nèi)嵌Servlet容器的Servlet、Filter、Listener三大組件時,
只需要將這些自定義組件通過ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean類注冊到容器中即可
組件注冊方式整合 Servlet
/* 自定義Servlet類 使用@Component注解將MyServlet類作為組件注入Spring容器。該類繼承自HTTPServlet, 通過HttpServletResponse對象向頁面輸出"hello MyServlet" */ @Component public class MyServlet 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 MyServlet"); } }
/* 嵌入式Servlet容器三大組件配置 @Configuration注解將該類標(biāo)注為配置類,getServlet()方法用于注冊自定義MyServlet, 返回ServletRegistrationBean類型的Bean對象 */ @Configuration public class ServletConfig { // 注冊Servlet組件 @Bean public ServletRegistrationBean<javax.servlet.Servlet> getServlet(MyServlet myServlet){ return new ServletRegistrationBean<javax.servlet.Servlet>(myServlet,"/myServlet"); } }
啟動測試,訪問myServlet,顯示數(shù)據(jù)說明成功整合Servlet組件
組件注冊方式整合Filter
/* 自定義Filter類 使用@Component注解將當(dāng)前MyFilter類作為組件注入到Spring容器中 MyFilter類實現(xiàn)Filter接口,重寫如下三個方法,在doFilter()方法中想控制臺打印"hello MyFilter" */ @Component 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("hello MyFilter"); filterChain.doFilter(servletRequest,servletResponse); } }
//注冊Filter組件 @Bean public FilterRegistrationBean<javax.servlet.Filter> getFilter(MyFilter myFilter){ FilterRegistrationBean<javax.servlet.Filter> registrationBean = new FilterRegistrationBean<>(myFilter); registrationBean.setUrlPatterns(Arrays.asList("/toLoginPage","/myFilter")); return registrationBean; }
啟動測試,訪問/myFilter,控制臺看到hello MyFilter
組件注冊方式整合Listener
/* 自定義Listener類 */ @Component public class MyListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("contextInitialized ..."); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("contextDestroyed ..."); } }
//注冊Listener組件 @Bean public ServletListenerRegistrationBean<java.util.EventListener> getServletListener(MyListener myListener){ return new ServletListenerRegistrationBean<>(myListener); }
程序啟動成功后,會自動打印輸出"contextInitialized ...",單擊坐下的Exit關(guān)閉會輸出銷毀的監(jiān)聽信息,如果直接強(qiáng)制關(guān)閉程序,無法打印監(jiān)聽信息。
- 注意:當(dāng)自定義的Servlet組件配置類ServletConfig全部注釋并重啟項目后,自定義的Servlet、Filter、Listener組件仍然生效。
- 原因:嵌入式Servlet容器對Servlet、Filter、Listener組件進(jìn)行了自動化識別和配置,而自定義的Servlet、Filter、Listener都繼承/實現(xiàn)了對應(yīng)的類/接口,同時自定義的這三個組件都使用了@Component注解,會自動被掃描為Spring組件。
路徑掃描整合Servlet三大組件
- 使用路徑掃描的方式整合三大組件,需要再自定義組件上分別添加@WebServlet、@WebFilter、@WebListener注解進(jìn)行聲明,并配置相關(guān)注解屬性,在主程序啟動類上使用@ServletComponentScan注解開啟組件掃描。
- 分別用以下三個注解代替@Component注解進(jìn)行配置三個組件
@WebFilter(value={"/antionLogin","/antionMyFilter"})
@WebListener
@WebServlet("/annotationServlet")
- 啟動類上加入
@ServletComponentScan
注解,開啟基于注解的組件掃描支持 - 對于Filter測試訪問"/antionLogin","/antionMyFilter",對于Servlet測試訪問"/annotationServlet",測試結(jié)果如上。
到此這篇關(guān)于詳解IDEA中SpringBoot整合Servlet三大組件的過程的文章就介紹到這了,更多相關(guān)SpringBoot整合Servlet三大組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何解決報錯:java.net.BindException:無法指定被請求的地址問題
在Linux虛擬機(jī)上安裝并啟動Tomcat時遇到啟動失敗的問題,通過檢查端口及配置文件未發(fā)現(xiàn)異常,后發(fā)現(xiàn)/etc/hosts文件中缺少localhost的映射,添加后重啟Tomcat成功,Tomcat啟動時會檢查localhost的IP映射,缺失或錯誤都可能導(dǎo)致啟動失敗2024-10-10MyBatis saveBatch 性能調(diào)優(yōu)的實現(xiàn)
本文主要介紹了MyBatis saveBatch 性能調(diào)優(yōu)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07Java日期操作方法工具類實例【包含日期比較大小,相加減,判斷,驗證,獲取年份等】
這篇文章主要介紹了Java日期操作方法工具類,結(jié)合完整實例形式分析了java針對日期的各種常見操作,包括日期比較大小,相加減,判斷,驗證,獲取年份、天數(shù)、星期等,需要的朋友可以參考下2017-11-11springboot springmvc拋出全局異常的解決方法
這篇文章主要為大家詳細(xì)介紹了springboot springmvc拋出全局異常的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06SpringBoot 統(tǒng)一異常處理的實現(xiàn)示例
本文主要介紹了SpringBoot 統(tǒng)一異常處理的實現(xiàn)示例,目的就是在異常發(fā)生時,盡可能地減少破壞,下面就來介紹一下,感興趣的可以了解一下2024-07-07SpringBoot 利用MultipartFile上傳本地圖片生成圖片鏈接的實現(xiàn)方法
這篇文章主要介紹了SpringBoot 利用MultipartFile上傳本地圖片生成圖片鏈接的實現(xiàn)方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03springboot 自定義權(quán)限標(biāo)簽(tld),在freemarker引用操作
這篇文章主要介紹了springboot 自定義權(quán)限標(biāo)簽(tld),在freemarker引用操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09