目錄
SpringBoot MVC異常處理
全局異常處理
局部異常處理
SpringBoot AOP
SpringBoot Servlet
Servlet
Filter
Listener
SpringBoot任務調度
服務器啓動後立刻執行
服務器啓動後定時執行
SpringBoot MVC異常處理
全局異常處理
原理
利用自動配置組件ErrorMvcAutoConfiguration創建了一個BasicErrorController對象,該Controller提供了兩個/error請求處理,一個返回json格式,一個返回html格式。當程序出現異常,會自動轉發調用/error請求,顯示錯誤處理結果。
自定義ErrorController
@Controller @RequestMapping("/error") public class MyErrorController extends AbstractErrorController{ public MyErrorController(ErrorAttributes errorAttributes) { super(errorAttributes); } public String getErrorPath() { return "/error"; } @RequestMapping(produces="text/html") public ModelAndView errorHtml(){ ModelAndView mav = new ModelAndView(); mav.setViewName("error1"); return mav; } }
局部異常處理
@Controller public class ExceptionController { @GetMapping("/ex/demo1") @ResponseBody public Object demo1(String no){ int result = Integer.parseInt(no)*100; return “運算結果爲:”+result; } @ExceptionHandler public String error(Exception e){ return “error2”; } }
SpringBoot AOP
導入spring-boot-starter-aop包
編寫切面組件,使用@Aspect、@Before、@After等標記
@Component @Aspect public class WatchBean { @Before("within(cn.xdl.controller..*)") public void mybefore(){ System.out.println("前置通知邏輯"); } @Around("within(cn.xdl.controller..*)") public Object myaround(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("環繞通知邏輯"); StopWatch watch = new StopWatch(); watch.start(); Object obj = pjp.proceed();//執行目標controller方法 watch.stop(); String target = pjp.getTarget().getClass().getName(); String method = pjp.getSignature().getName(); System.out.println(target+"類"+method+"方法執行了"+watch+"毫秒"); return obj; } }
SpringBoot Servlet
需要在啓動類前,使用@ServletComponentScan標記
Servlet
採用@WebServlet配置。
@WebServlet(name="helloservlet",loadOnStartup=1,urlPatterns={"/hello","/hello.do"}) public class HelloServlet extends HttpServlet{ public void service( HttpServletRequest request,HttpServletResponse response) throws IOException{ response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession();//獲取session //session.invalidate();//銷燬 out.println("Hello Servlet in SpringBoot"); out.println("在線人數:"+request.getServletContext().getAttribute("count")); out.close(); } }
Filter
採用@WebFilter配置,如果有多個Filter,按類名字典順序執行調用。
//@WebFilter(urlPatterns={"/hello"}) @WebFilter(servletNames={"helloservlet"}) public class BHelloFilter implements Filter{ public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Hello Filter in SpringBoot1"); chain.doFilter(request, response);//執行後續處理Filter或Servlet } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
Listener
採用@WebListener配置。
@WebListener public class HelloListener implements HttpSessionListener,ServletContextListener{ private ServletContext application; public void sessionCreated(HttpSessionEvent arg0) { Long count = (Long)application.getAttribute(“count”); count++; application.setAttribute(“count”,count); } public void sessionDestroyed(HttpSessionEvent arg0) { Long count = (Long)application.getAttribute(“count”); count–; application.setAttribute(“count”,count); } public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } public void contextInitialized(ServletContextEvent arg0) { long count = 0; arg0.getServletContext().setAttribute(“count”, count); application = arg0.getServletContext(); } }
SpringBoot任務調度
服務器啓動後立刻執行
SpringBoot提供了兩個接口,可以實現啓動服務器後立刻執行任務調度,分別是ApplicationRunner和CommandLineRunner。
ApplicationRunner
@Component @Order(2) public class MyTask2 implements ApplicationRunner{ public void run(ApplicationArguments args) throws Exception { System.out.println("執行任務2"); } }
CommandLineRunner
@Component @Order(1) public class MyTask3 implements CommandLineRunner{ public void run(String... args) throws Exception { System.out.println("執行任務3"); } }
提示: 多個任務可以使用@Order註解定義執行順序,採用同步模式執行。
服務器啓動後定時執行
@Component @EnableScheduling//開啓計劃調用功能 public class MyTask6 { //利用corn表達式指定計劃執行時機 // @Scheduled(cron=“30 31 15 7 12 ?”) @Scheduled(cron=“0/5 * * * * ?”) public void execute(){ System.out.println(“執行了任務6”+new Date()); } }
Cron 表達式由6部分構成,也可以是7個。從左到右,分別表示
秒 分 時 日 月 星期 年 秒: 0-59 分: 0-59 時: 0-23 日: 1-31 月: 1-12 星期:1-7 1表示星期日,7表示星期六 年:1970-2099 ?: 用於日和星期,指定日,星期就用?;指定星期,日用? *: 用於各個部分,表示任意值 /: 表示增量, 3/5 表示3、8、13、18等 L: 用於日和星期,表示最後一天或星期最後一天