zoukankan      html  css  js  c++  java
  • 整合Freemarker视图层和整合jsp视图层和全局捕获异常

    SpringBoot静态资源访问

    1.静态资源:访问 js / css /图片,传统web工程,webapps

    springboot 要求:静态资源存放在resource目录下(可以自定义文件存放)

    2.整合Freemarker视图层

    使用Freemarker模板引擎渲染web视图

    pom文件引入

              <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-freemarker</artifactId>
             </dependency>

     3.创建SpringBoot整合jsp,一定要为war类型

    不要把jsp页面存放在resource目录下    ,可能产生被别人访问到,jsp不能被别人访问

             <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </dependency>
            <!-- springboot 外部tomcat支持 -->
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-jasper</artifactId>
                <scope>test</scope>
            </dependency>

    4.SpringBoot整合全局捕获异常

    相当于整个web请求项目全局捕获异常  ,错误记得存放在日志中

    使用Aop技术,采用异常通知

    //全局捕获异常案例
    //@ExceptionHandler--拦截错误
    //1.捕获返回json格式
    //@ResponseBody--返回json格式
    //@modeAndView--返回视图页面
    //2.捕获返回页面

    应用场景:

     //如果每个方法都可能会发生异常,每个方法都加上try不好  采用全局捕获异常
        @RequestMapping("/hello")
        public String hello(int i) {
           try {
               int j=1/i; 
           }catch (Exception e) {
            return "系统错误";
        }
           
           return "success";
          
       }
    package com.example.demo.controller.error;
    
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @ControllerAdvice(basePackages="com.example.demo.controller")
    public class ErrorHandler {
      @ExceptionHandler(RuntimeException.class)
      @ResponseBody//返回json格式
      public Map<String, Object> errorResult(){
          Map<String, Object> error=new HashMap<String, Object>();
          error.put("errorcode", "500");
          error.put("errormsg", "全局捕获异常系统错误");
          return error;
         
      }
    }
  • 相关阅读:
    java+selenium自动化-IE浏览器搭建自动化环境
    python中的opencv
    随机森林参数说明
    剑指offer
    Python中常用的包--sklearn
    Anaconda安装,jupyter notebook 使用说明
    C++中的Public 、Private、Protected 区别
    C++类中的Static关键字二
    C++类中的Static关键字
    c语言二级指针内存模型
  • 原文地址:https://www.cnblogs.com/tanlei-sxs/p/9624426.html
Copyright © 2011-2022 走看看