Spring框架(十七)SpringBoot框架+SpringBoot MVC异常处理+SpringBoot AOP+SpringBoot ServletSpringBoot任务调度

目录
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: 用于日和星期,表示最后一天或星期最后一天

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值