SpringBoot——小试牛刀三阶段

  1. SpringBoot的父级依赖

1)创建父级工程pom.xml

  1. 在父级工程里创建子module,pom.xml如下

        SpringBoot_Parent    com.carry    1.0-SNAPSHOT4.0.0SpringBoot_Child1            org.springframework.boot        spring-boot-starter-web    

22.  访问静态资源:

在SpringBoot中加载静态资源和在普通的web应用中不太一样。默认情况下,Spring Boot从classpath的/static,/public 或/META-INF/resources文件夹或从ServletContext根目录提供静态内容

#设定静态文件路径,js,css,image等

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

23.  自定义消息转化器

只需要在类中添加消息转化器的@Bean,就会被Spring Boot自动加入到容器中。

// SpringBoot默认配置了消息转换器// 定义消息转换器@Beanpublic StringHttpMessageConverter stringHttpMessageConverter() {    StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("ISO8859-1"));    return converter;}

24.  使用FastJson解析Json数据:

SpringBoot默认配置的是Jackson。

使用FastJson解析Json数据:

<!-- fastjson的依赖 --><dependency>        <groupId>com.alibaba</groupId>        <artifactId>fastjson</artifactId>        <version>1.2.46</version>    </dependency>

配置FastJson有两种方式:

第一种:让启动类继承WebMvcConfigurerAdapter

public class SpringApplications extends WebMvcConfigurerAdapter{@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {   // 创建FastJson的消息转换器    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();    // 创建FastJson的配置对象    FastJsonConfig config = new FastJsonConfig();    // 对Json数据进行格式化    config.setSerializerFeatures(SerializerFeature.PrettyFormat);    converter.setFastJsonConfig(config);    converters.add(converter);}}

乱码解决:

把springboot的reponse编码设置为utf-8这个功能开启就好了

spring.http.encoding.force=true

注意:FastJson可以对日期进行格式化,可使用如下注解

@JSONField(format = "yyyy-MM-dd HH")

private Date date;

第二种:@Bean注入

在启动类中添加如下代码

@Beanpublic HttpMessageConverters fastJsonMessageConverter() {    // 创建FastJson的消息转换器    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();    // 创建FastJson的配置对象    FastJsonConfig config = new FastJsonConfig();    // 对Json数据进行格式化    config.setSerializerFeatures(SerializerFeature.PrettyFormat);    converter.setFastJsonConfig(config);    HttpMessageConverter<?> con = converter;    return new HttpMessageConverters(con);}

25.  自定义拦截器:

有些时候我们需要自己配置SpringMVC而不是采用默认,比如说增加一个拦截器,这个时候就得通过继承WebMvcConfigurerAdapter然后重写父类中的方法进行扩展。

注意:需要在启动类中定义扫描该文件

@Configuration // 声明这是一个配置 public class MyInterceptor extends WebMvcConfigurerAdapter {@Overridepublic void addInterceptors(InterceptorRegistry registry) {    HandlerInterceptor interceptor = new HandlerInterceptor() {        @Override        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {            System.out.println("自定义拦截器......");            return true;        }        @Override        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {        }        @Override        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {        }    };    registry.addInterceptor(interceptor).addPathPatterns("/**");}}

26.  定义全局异常处理器:

创建一个全局异常处理类,如下:

// 全局异常处理器@ControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(Exception.class)@ResponseBodypublic Map<String, Object> allExceptionHandler(Exception exception) throws Exception {    Map<String, Object> map = new HashMap<String, Object>();    map.put("errorCode", 500);    map.put("errorMsg", exception.toString());    return map;}}

27.  异步调用:

在项目中,当访问其他接口较慢或者做耗时任务时,不想程序一直卡在耗时任务上,想程序能够并行执行,我们可以使用多线程来并行的处理任务,SpringBoot提供了异步处理方式@Async.

注意:需要在启动类添加@EnableAsync //开启异步调用

@Servicepublic class AsyncServiceImpl implements AsyncService {private static Random random = new Random();@Async@Overridepublic Future<String> doTask1() throws Exception {    System.out.println("任务一开始执行");    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    System.out.println("任务一结束,耗时:" + (end -start) + "毫秒");    return new AsyncResult<>("任务一结束");}@Async@Overridepublic Future<String> doTask2() throws Exception {    System.out.println("任务二开始执行");    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    System.out.println("任务二结束,耗时:" + (end -start) + "毫秒");    return new AsyncResult<>("任务二结束");}@Async@Overridepublic Future<String> doTask3() throws Exception {    System.out.println("任务三开始执行");    long start = System.currentTimeMillis();    Thread.sleep(random.nextInt(10000));    long end = System.currentTimeMillis();    System.out.println("任务三结束,耗时:" + (end -start) + "毫秒");    return new AsyncResult<>("任务三结束");}}

28.  SpringBoot整合JSP

  1.  pom文件中添加如下代码:注意需要使用spring-boot-starter-parent的版本为1.4.0及以上版本

    4.0.0com.fengyaoSpringBoot_Jsp1.0-SNAPSHOTjar    org.springframework.boot    spring-boot-starter-parent    1.4.0.RELEASE         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>    <java.version>1.8</java.version>            org.springframework.boot        spring-boot-starter-web                org.springframework.boot        spring-boot-starter-tomcat        provided                org.apache.tomcat.embed        tomcat-embed-jasper                        org.springframework.boot        spring-boot-starter-test        test                            org.springframework.boot            spring-boot-maven-plugin            

2)需要在application.properties中添加如下代码:

# 页面默认前缀目录

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

# 响应页面默认后缀

spring.mvc.view.suffix=.jsp

3)在main目录下新建webapp文件夹,然后新建jsp的存储目录

4)启动类文件如下:

@SpringBootApplicationpublic class SpringApp extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {    return builder.sources(SpringApp.class);}public static void main(String[] args) {    SpringApplication.run(SpringApp.class, args);}}

29.  SpringBoot整合Freemarker:

1)在pom.xml文件中添加如下依赖

<!-- springboot不建议使用jsp,使用模板引擎,比如themleaf,velocity,freemarker    整合freemarker -->    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-freemarker</artifactId>    </dependency>

2)在main文件夹下创建webapp/templates/show.ftl文件

3)在application.properties下面添加如下配置:

#springboot整合freemarker

spring.freemarker.allow-request-override=false

spring.freemarker.cache=true

spring.freemarker.check-template-location=true

spring.freemarker.charset=utf-8

spring.freemarker.content-type=text/html

spring.freemarker.expose-request-attributes=false

spring.freemarker.expose-session-attributes=false

spring.freemarker.expose-spring-macro-helpers=false

spring.freemarker.suffix=.ftl

spring.freemarker.template-loader-path=classpath:/templates

30.  SpringBoot整合Thymeleaf:

1)在pom.xml文件中添加如下依赖

 <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-thymeleaf</artifactId>    </dependency>    <dependency>        <groupId>net.sourceforge.nekohtml</groupId>        <artifactId>nekohtml</artifactId>        <version>1.9.22</version>    </dependency>

2)在main文件夹下创建webapp/templates/tests.html文件

3)在application.properties下面添加如下配置:

#springboot整合thymeleaf

#

spring.thymeleaf.cache=false

## 检查模板是否存在,然后再呈现

spring.thymeleaf.check-template-location=true

# Content-Type值

spring.thymeleaf.content-type=text/html

# 启用MVC Thymeleaf视图分辨率

spring.thymeleaf.enabled=true

## 应该从解决方案中排除的视图名称的逗号分隔列表

spring.thymeleaf.excluded-view-names=

# 模板编码

spring.thymeleaf.mode=LEGACYHTML5

# 在构建URL时预先查看名称的前缀

spring.thymeleaf.prefix=classpath:/templates/

# 构建URL时附加查看名称的后缀

spring.thymeleaf.suffix=.html

# 链中模板解析器的顺序

#spring.thymeleaf.template-resolver-order=0

# 可以解析的视图名称的逗号分隔列表

#spring.thymeleaf.view-names=

#thymeleaf end

本文分享自微信公众号 - Java学习进阶手册(javastudyup)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论

暂无评论