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工程下 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM