zoukankan      html  css  js  c++  java
  • spring boot 整合web开发(一)

    • 目录

      springboot 整合web开发
    • 返回json数据
    • 静态资源访问
    • 文件上传
    • 全局异常

     1、返回json数据

    springboot默认的是jackson-databind做为json处理器、也可以使用自定义转换器:gson、fastjson

    gson集成方式为:在pom文件中排除jackson-databind jar包,添加gson包。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
    </dependency>

    springboot默认提供了Gson自动转换类GsonHttpMessageConvertersConfiguration,因此Gson依赖添加成功后,可以像使用json-databind那样使用Gson。但是如果想格式化日期等操作得需要自己自定义。

    @Configuration
    public class GsonConfig {
    
        @Bean
        GsonHttpMessageConverter gsonHttpMessageConverter() {
            GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
            GsonBuilder builder = new GsonBuilder();
            builder.setDateFormat("yyyy-MM-dd");
            builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
            Gson gson = builder.create();
            gsonHttpMessageConverter.setGson(gson);
            return gsonHttpMessageConverter;
        }
    
    }

    fastJson集成方式:在pom文件中排除jackson-databind jar包,添加fastjson

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.56</version>
    </dependency 

    配置fastjson的HttpMessageConverter

    @Configuration
    public class MyFastJsonConfig {
    
        @Bean
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            FastJsonConfig config = new FastJsonConfig();
            config.setDateFormat("yyyy-MM-dd");
            config.setCharset(Charset.forName("UTF-8"));
            config.setSerializerFeatures(
                    SerializerFeature.WriteClassName,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteNullListAsEmpty,
                    SerializerFeature.WriteNullStringAsEmpty
            );
            converter.setFastJsonConfig(config);
            return converter;
        }
    }
    

     对于FastJsonHttpMessageConverter的配置,还有另一种方式。实现WevMvcConfigurer接口(spring5.0之前继承WebMvcConfigurerAdapter类来实现)

    @Configuration
    public class MyWebMvcConfig implements WebMvcConfigurer {
    
        //处理json
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            FastJsonConfig config = new FastJsonConfig();
            config.setDateFormat("yyyy-MM-dd");
            config.setCharset(Charset.forName("UTF-8"));
            config.setSerializerFeatures(
                    SerializerFeature.WriteClassName,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteNullListAsEmpty,
                    SerializerFeature.WriteNullStringAsEmpty
            );
            converter.setFastJsonConfig(config);
            converters.add(converter);
        }
    
        //自定义静态资源位置
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**")
                    .addResourceLocations("classpath:/static/");
        }
    }
    

     2、静态资源访问

    springboot默认会过滤所有的静态资源,默认静态资源5个位置(classpath:/META-INF/resources/、classpath:/resources/、classpath:/static/、classpath:/public/、/),优先级依次降低。

    自定义过滤策略:1)、可以在application.properties直接定义过滤规则

    spring.mvc.static-path-pattern=/static/**

    spring.resources.static-locations=classpath:/static

     2)、java编码实现

    @Configuration
    public class MyWebMvcConfig implements WebMvcConfigurer {
    
        //处理json
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            FastJsonConfig config = new FastJsonConfig();
            config.setDateFormat("yyyy-MM-dd");
            config.setCharset(Charset.forName("UTF-8"));
            config.setSerializerFeatures(
                    SerializerFeature.WriteClassName,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteNullListAsEmpty,
                    SerializerFeature.WriteNullStringAsEmpty
            );
            converter.setFastJsonConfig(config);
            converters.add(converter);
        }
    
        //自定义静态资源位置
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**")
                    .addResourceLocations("classpath:/static/");
        }
    }

    3、文件上传

    文件上传一共涉及两个组件,一个是CommonsMultipartResolver基于commons-fileupload来处理,另一个是StandardServletMultipartResolver基于serlver3.0multipart 。springboot默认采用的是StandardServletMultipartResolver做为上传组件。

    如果想使用CommonsMultipartResolver做为上传组件代码如下:

    pom文件需要加入common jar包

     <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>1.4</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>

    @Configuration
    public class MyCommonsMultipartResolver {
    
        @Bean
        public CommonsMultipartResolver commonsMultipartResolver() {
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
            commonsMultipartResolver.setResolveLazily(true);//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
            commonsMultipartResolver.setMaxUploadSize(1024);
            commonsMultipartResolver.setDefaultEncoding("UTF-8");
            return commonsMultipartResolver;
        }
    }
    

     4、全局异常处理

    关键字@ControllerAdvice

    1)、返回resonse代码如下,上传文件大小超过限制就会输出到页面。

    @ControllerAdvice
    public class CustomerExceptionHandler {
    
        @ExceptionHandler(MaxUploadSizeExceededException.class)
        public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse resp) throws IOException {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.write("上传文件大小超限");
            out.flush();
            out.close();
        }
    }

    2)、返回ModelAndView

    @ControllerAdvice
    public class CustomerExceptionHtmlHandler {
    
        @ExceptionHandler(MaxUploadSizeExceededException.class)
        public ModelAndView uploadException(MaxUploadSizeExceededException e) throws IOException {
           ModelAndView view = new ModelAndView();
           view.addObject("msg","上传文件超限");
           view.setViewName("/error");
           return view;
        }
    }

    @ControllerAdvice还可以配置全局参数,具体代码如下

    @ControllerAdvice
    public class GlobalConfig {

    @ModelAttribute(value = "info")
    public Map<String,String> userInfo() {
    Map<String,String> map = new HashMap<>();
    map.put("usename","路遥");
    map.put("gender","男");
    return map;
    }
    }
    @RestController
    public class GlobalController {

    @GetMapping("/global")
    public void globalParma(Model model) {
    Map<String, Object> map = model.asMap();
    Set<String> strings = map.keySet();
    Iterator<String> iterator = strings.iterator();
    while (iterator.hasNext()) {
    String next = iterator.next();
    Object o = map.get(next);
    System.out.println(next + ">>>>>>" + o);
    }
    }
    }

    以上所有代码都在:https://github.com/FadeHub/spring-boot-learn 下面的spring-boot-web工程下 

  • 相关阅读:
    OpenMp之reduction求和
    C++中的字节对齐
    java mail邮件发送(带附件) 支持SSL
    linux下通过命令启动多个终端运行对应的命令和程序
    JAVA数组的定义及用法
    ThreadPoolExecutor使用介绍
    命令拷屏之程序分析
    java实现第五届蓝桥杯供水设施
    java实现第五届蓝桥杯供水设施
    java实现第五届蓝桥杯供水设施
  • 原文地址:https://www.cnblogs.com/treeshu/p/11235292.html
Copyright © 2011-2022 走看看