美文网首页
2、spring-boot web 使用

2、spring-boot web 使用

作者: KissGoodby | 来源:发表于2018-10-13 17:11 被阅读0次

参考博客
月光中的污点

1、spring-boot整合fastJson

  1. 添加依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.35</version>
</dependency>
  1. 整合fastJson
    配置配置类FastJsonWebConfig.java
@Component
public class FastJsonWebConfig {

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        return new HttpMessageConverters(converter);
    }
}

这样整合基本完成

  1. 测试
    创建实体类
public class User implements Serializable {

    private Integer id;

    private String userName;

    private String password;

    @JSONField(format = "yyyy-MM-dd")
    private Date birthday;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

创建controller

@Controller
@RequestMapping(value = "fastjson")
public class FastJsonController {

    @RequestMapping(value = "/test")
    @ResponseBody
    public User test() {
        User user = new User();
        user.setBirthday(new Date());
        user.setId(1);
        user.setPassword("pass");
        user.setUserName("user");
        int i = 1 / 0;
        return user;
    }
}

2、整合自定义过虑器

  1. 创建自定义filter
public class TimeFilter implements Filter {

    private static Logger LOGGER = LoggerFactory.getLogger(TimeFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("=====================================================");
        LOGGER.info("初始化过虑器");
        LOGGER.info("=====================================================");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        filterChain.doFilter(servletRequest, servletResponse);
        LOGGER.info("filter耗时:{}", System.currentTimeMillis() - start);
    }

    @Override
    public void destroy() {
        LOGGER.info("=====================================================");
        LOGGER.info("销毁过虑器");
        LOGGER.info("=====================================================");
    }
}
  1. 注册自定义filter,有两种方式可以将过虑器生效:
  • 使用 @Component 注解
  • 添加到过滤器链中,此方式适用于使用第三方的过滤器。将过滤器写到 WebConfig 类中
    第一种方式代码:
@Configuration
public class TimeFilterRegisterBean {

    @Bean
    public FilterRegistrationBean timeFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();

        TimeFilter timeFilter = new TimeFilter();
        registrationBean.setFilter(timeFilter);

        List<String> filterUrl = new ArrayList<>();
        filterUrl.add("/*");
        registrationBean.setUrlPatterns(filterUrl);
        return registrationBean;
    }
}

第二种方式:

@SpringBootApplication
public class Application implements ServletContextInitializer{

    private static Logger LOGGER = LoggerFactory.getLogger(Application.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        LOGGER.info("spring容器启动。。。。");
        //另一种方式添加filter
        servletContext.addFilter("timeFilter", new TimeFilter()).addMappingForUrlPatterns(EnumSet.of().of(DispatcherType
                .REQUEST), true, "/*");
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
    }
}

3、整合切面

  1. 添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  1. 添加切面类
@Aspect
@Component
public class TimeAspect {

    private static Logger LOGGER = LoggerFactory.getLogger(TimeAspect.class);

    @Around(value = "execution(* com.hui.wang.spring.boot.controller.FastJsonController..*(..))")
    public Object method(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        LOGGER.info("===================================================");
        LOGGER.info("TimeAspect开始处理");
        LOGGER.info("===================================================");

        Object[] args = proceedingJoinPoint.getArgs();
        for (Object arg : args) {
            LOGGER.info("参数为:{}", arg);
        }

        long start = System.currentTimeMillis();
        Object object = proceedingJoinPoint.proceed();
        LOGGER.info("方法耗时:{}", System.currentTimeMillis() - start);

        return object;
    }
}

4、统一处理异常

  1. 编写一个类充当全局异常的处理类,需要使用 @ControllerAdvice 和 @ExceptionHandler 注解:
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    private static Logger LOGGER = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String,Object> defaultExceptionHandler(Exception e) {
        LOGGER.error("异常", e);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", e.getMessage());
        return map;
    }
}

全局处理异常时一定不要忘记打印错误异常日志,否者异常就会被吞掉,这仅仅是配置方法,生成环境全局处理异常还需考虑谨慎,全面

相关文章

网友评论

      本文标题:2、spring-boot web 使用

      本文链接:https://www.haomeiwen.com/subject/vmgoaftx.html