SpringBoot——小试牛刀三阶段

Easter79
• 阅读 332
  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源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
2年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Stella981 Stella981
2年前
SpringBoot——小试牛刀三阶段
21.SpringBoot的父级依赖1)创建父级工程pom.xml2)在父级工程里创建子module,pom.xml如下<?xml version"1.0" encoding"UTF8"?<project xmlns"http://maven.apache.org/POM/4.0.
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k