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