Spring Boot

五、SpringBoot Web应用-2 (error &

2018-09-14  本文已影响6人  Class鸣

1、错误处理机制

1)、SpringBoot默认的错误处理机制

2)、如果定制错误响应:

1. 如何定制错误的页面;

1)有模板引擎的情况下;error/状态码;

2)没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
3)以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;

2. 如何定制错误的json数据;

1)自定义异常处理&返回定制json数据;

public class UserNotExistException extends RuntimeException {

   public UserNotExistException() {
       super("用户不存在");
   }
}
@ControllerAdvice
public class MyExceptionHandler {

    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map<String,Object> handleException(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        return map;
    }
}
@ControllerAdvice 的声明内容
  @Target(ElementType.TYPE)  
  @Retention(RetentionPolicy.RUNTIME)  
  @Documented  
  @Component  
  1. 设置什么情况下调用异常
@ResponseBody
    @RequestMapping("/hello")
    public  String hello(@RequestParam("user") String user){
        if(user.equals("aaa")){
            throw new UserNotExistException();
        }
        return "Hello World";
    }

3)转发到/error进行自适应响应效果处理

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码  4xx 5xx
        /**
         * Integer statusCode = (Integer) request
         .getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message","用户出错啦");

        request.setAttribute("ext",map);
        //转发到/error
        return "forward:/error";
    }
}

3. 将我们的定制数据携带出去;

​ 1. 完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;【不方便】

​ 2. 页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到; 容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;

//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

    //返回值的map就是页面和json能获取的所有字段
    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
        map.put("company","atguigu");

        //我们的异常处理器携带的数据
        Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
        map.put("ext",ext);
        return map;
    }
}

8、配置嵌入式Servlet容器

1、如何定制和修改Servlet容器的相关配置;

1)修改和server有关的配置(ServerProperties【也是EmbeddedServletContainerCustomizer】);

server.port=8081
server.context‐path=/crud
server.tomcat.uri‐encoding=UTF‐8
//通用的Servlet容器设置
server.xxx
//Tomcat的设置
server.tomcat.xxx

2) 编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;来修改Servlet容器的
配置

@Bean  //一定要将这个定制器加入到容器中
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
    return new EmbeddedServletContainerCustomizer() {

        //定制嵌入式的Servlet容器相关的规则
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.setPort(8083);
        }
    };
}

2、注册Servlet三大组件【ServletFilterListener

前提是自己也要编写ServletFilterListener`方法【下面就不示范这三个类的编写了】

  1. ServletRegistrationBean
@Bean
public ServletRegistrationBean myServlet(){
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
    return registrationBean;
}
  1. FilterRegistrationBean
@Bean
public FilterRegistrationBean myFilter(){
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new MyFilter());
    registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
    return registrationBean;
}
  1. ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean myListener(){
    ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
    return registrationBean;
}

3、使用内置的Servlet容器

目前支持3中servlet容器

  1. tomcat
  2. jetty
  3. undertow
  1. 排除默认使用的Tomcat
<!-- 引入web模块 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <exclusions>
      <!-- 排除tomcat -->
      <exclusion>
         <artifactId>spring-boot-starter-tomcat</artifactId>
  <groupId>org.springframework.boot</groupId>
      </exclusion>
   </exclusions>
</dependency>
  1. 引入
<!--引入其他的Servlet容器-->
<dependency>
   <artifactId>spring-boot-starter-jetty</artifactId>
   <groupId>org.springframework.boot</groupId>
</dependency>
<!--引入其他的Servlet容器-->
<dependency>
   <artifactId>spring-boot-starter-undertow</artifactId>
   <groupId>org.springframework.boot</groupId>
</dependency>

3、使用外置的Servlet容器

步骤

1)添加服务

  1. 必须在创建的时候,创建war项目
    创建`war`项目
  2. 添加Tomcat服务
  3. 打开配置界面


    打开配置界面
  4. 配置服务器
选择项目
  1. 配置项目 webapp中的文件
打开配置页面 配置 webapp 文件夹 和 web.xml 文件

2)必须编写一个SpringBootServletInitializer的子类,并调用configure方法

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        // Customize the application or call application.sources(...) to add sources
        // Since our example is itself a @Configuration class (via @SpringBootApplication)
        // we actually don't need to override this method.
        return application;
    }
}

请记住,无论你放入什么sources只是一个SpringApplicationContext,通常任何已经有效的东西都应该在这里工作。可能有一些bean可以在以后删除,让Spring Boot为它们提供自己的默认值,但应该可以先得到一些工作。

静态资源可以移动到类路径根目录中/public/static/resources/META-INF/resources)。相同messages.properties(Spring Boot会在类路径的根目录中自动检测到这一点)。

4、使用外置Servlet容器

1)目录结构

实例:


目录

2)jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>HELLO</h1>
    <a href="/hello" ><h2>success</h2></a>
</body>
</html>

3)视图解析器配置

spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp

4)控制器

@Controller
public class controller {
    @GetMapping("/hello")
    public String success(Model model) {
        model.addAttribute("hello", "你好!");
        return "success";
    }
}

5)转发至的jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>success</h1>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读