SpringBoot框架的环境搭建与使用

一.springboot概述

  1. Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的创建、运行、调试、部署等。使用Spring Boot可以做到专注于Spring应用的开发,而无需过多关注XML的配置。Spring Boot使用“习惯优于配置”的理念,简单来说,它提供了一堆依赖打包,并已经按照使用习惯解决了依赖问题。使用Spring Boot可以不用或者只需要很少的Spring配置就可以让企业项目快速运行起来。

  2. Spring Boot是开发者和Spring 本身框架的中间层,帮助开发者统筹管理应用的配置,提供基于实际开发中常见配置的默认处理(即习惯优于配置),简化应用的开发,简化应用的运维;总的来说,其目的Spring Boot就是为了对Java web 的开发进行“简化”和加“快”速度,简化开发过程中引入或启动相关Spring 功能的配置。这样带来的好处就是降低开发人员对于框架的关注点,可以把更多的精力放在自己的业务代码上。同时随着微服务概念的推广和实践,Spring Boot的精简理念又使其成为Java微服务开发的不二之选,也可以说,Spring Boot其实就是为了微服务而生的Java web框架。

二. springboot的核心功能

可独立运行的Spring项目:Spring Boot可以以jar包的形式独立运行。

内嵌的Servlet容器:Spring Boot可以选择内嵌Tomcat、Jetty或者Undertow,无须以war包形式部署项目。

简化的Maven配置:Spring提供推荐的基础 POM 文件来简化Maven 配置。

自动配置Spring:Spring Boot会根据项目依赖来自动配置Spring 框架,极大地减少项目要使用的配置。

提供生产就绪型功能:提供可以直接在生产环境中使用的功能,如性能指标、应用信息和应用健康检查。

无代码生成和xml配置:Spring Boot不生成代码。完全不需要任何xml配置即可实现Spring的所有配置。

三. springboot的相关好处

  1. 以往的项目整合起来是比较繁琐复杂的,而且存在架包冲突的问题,这时候SpringBoot应运而生了,SpringBoot也就是用来做这个的。

  2. SpringBoot是一个快速开发的框架,能过快速整合第三方框架,他是如何快速整合的呢?其实他是的基本原来是Maven依赖关系,Maven的集成,完全采用注解化,简化XML配置,内嵌HTTP服务器(Tomcate,jetty),默认嵌入Tomcate,最终以Java应用程序进行执行。

四. 如何快速使用idea开发工具来配置一个MAVEN项目(体验)

  1. 配置pom.xml文件添加相关依赖JAR包(父类配置2.X为了后面的SpringCloud)

    <!-- Inherit defaults from Spring Boot -->
    <!--所有的springboot项目都需要继承父类-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>
    ​
    <!-- Add typical dependencies for a web application -->
    <!--web项目的启动器-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
  2. 创建对应的控制器TestController和对应的里面的代码

  3. @RestController
    @RequestMapping("/")
    public class TestController {
        @RequestMapping("/index")
        public String index(){
            return "hello Springboot";
        }
    }
  4. 编写对应的引导类注意,要和controller在同一个级别目录下

  5. @SpringBootApplication
    public class SpringbootTestApplication {
        public static void main(String[] args) {
            SpringApplication.run(SpringbootTestApplication.class,args);
        }
    }
  6. 启动成功后,控制台会进行相应的信息的输出以及对应的端口号的显示http://localhost:8080/index

  7. 在resources资源文件夹下新建一个file application.properties文件

  8. 在里面进行相关的配置项目名字和端口号的配置

  9. server.port=9999
    server.servlet.context-path=/springboot
  10. http://localhost:9999/springboot/index

  11. 如果是yml文件application.yml

  12. server:
      port: 9999
      servlet:
        context-path: /springboot

五.yml(yml文件介绍)

一种基于Unicode容易阅读,容易和脚本语言交互的,用来表达资料序列的编程语言。适应场景 脚本语言:由于实现简单,解析成本很低,YAML 特别适合在脚本语言中使用 序列化: YAML是由宿主语言数据类型直转,的比较适合做序列化。 配置文件:写 YAML 要比写 XML 快得多(无需关注标签或引号),并且比 INI 文档功能更强。由于兼容性问题,不同语言间的数据流转建议不要用 YAML。 语言优点 YAML易于人们阅读。 YAML数据在编程语言之间是可移植的。 YAML匹配敏捷语言的本机数据结构。 YAML具有一致的模型来支持通用工具。 YAML支持单程处理。 YAML具有表现力和可扩展性。 YAML易于实现和使用。 YAML 语法 使用空格 Space 缩进表示分层,不同层次之间的缩进可以使用不同的空格数目,但是同层元素一定左对齐,即前面空格数目相同(不能使用 Tab,各个系统 Tab对应的 Space 数目可能不同,导致层次混乱) ‘#’表示注释,只能单行注释,从#开始处到行尾 破折号后面跟一个空格(a dash and space)表示列表 用冒号和空格表示键值对 key: value 简单数据(scalars,标量数据)可以不使用引号括起来,包括字符串数据。用单引号或者双引号括起来的被当作字符串数据,在单引号或双引号中使用C风格的转义字符 Sequence of Scalars 简单数据列表

  1. 利用yml文件添加对应的数据进行解析

  2. person:
      username: admin
      password: 123456
          #配置数组集合
    city:
      - beijing
      - tianjing
      - chongqing
    ​
    #country: [beijing,wuhan]
    ​
    ​
    ​
    person:
      username: admin
      password: 123456
    food: kfc
    ​
    #配置数组集合(对象)
    student:
      - name: tom
        age: 12
        addr: beijing
      - name: jim
        age: 23
        addr: tianjing
    ​
    teacher: [{name: jim,age: 13,addr: beijing},{name: kkk,age: 12,addr: wuhan}]
    ​
    ​
    map:
      key1: value1
      key2: value2
    person:
      name: admin
      age: 12
      addr: wuhan
  3. <!--添加执行器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
  4. 单一解析yml里面的一个key文件

    package com.chinasoft.springbootTest.controller;
    ​
    ​
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.jdbc.JdbcProperties;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    ​
    @RestController
    @RequestMapping("/")
    ​
    public class TestController {
    ​
        private static final Logger log= LoggerFactory.getLogger(TestController.class);
     
        @Value("${food}")
        private String food;
    ​
    ​
    ​
    ​
        @RequestMapping("/index")
        public String index(){
           // log.info(jdbc.getUsername());
            //log.info(jdbc.getPassword());
            return "hello Springboot"+food;
        }
    ​
        public String getFood() {
            return food;
        }
    ​
        public void setFood(String food) {
            this.food = food;
        }
    ​
    ​
    }

  5. package com.chinasoft.springbootTest.controller;
    
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/")
    @ConfigurationProperties(prefix = "person")
    public class TestController {
        private String username;
        private String password;
    
    
        @RequestMapping("/index")
        public String index(){
            return "hello Springboot"+username+password;
        }
    
        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;
        }
    }
  6. 最后一种也是最常用的一种

    创建config的package然后创建Jdbc.properties

    package com.chinasoft.springbootTest.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ConfigurationProperties(prefix = "person")
    public class JdpcProperties {
        private String username;
        private String password;
    
        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;
        }
    }
package com.chinasoft.springbootTest.controller;


import com.chinasoft.springbootTest.config.JdpcProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.JdbcProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")

public class TestController {
    @Autowired
    private JdpcProperties jdbc;


    @RequestMapping("/index")
    public String index(){
        return "hello Springboot"+jdbc.getUsername()+jdbc.getPassword();
    }


}

那么很神奇的地方在于@ConfigurationProperties(prefix = "person")可以作用在方法上

package com.chinasoft.springbootTest.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JdbcConfig {
    @Bean
    @ConfigurationProperties(prefix = "person")
    public JdpcProperties getData(){
        JdpcProperties j=new JdpcProperties();
        return j;
    }

}
public class JdpcProperties {
    private String username;
    private String password;

    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;
    }
}

@RestController
@RequestMapping("/")
public class TestController {

    private static final Logger log= LoggerFactory.getLogger(TestController.class);
    @Autowired
   private JdbcConfig jdbc;

    @RequestMapping("/index")
    public String index(){
        return "hello Springboot"+jdbc.getData().getUsername();
    }
}

那么我们在springboot项目中的SSM框架中如何来配置呢?

//package com.chinasoft.springboot.config;//package com.chinasoft.springboot_mybatis.config;
//
//import lombok.Data;
//import org.springframework.boot.context.properties.ConfigurationProperties;
读取application.yml里面的jdbc的key
//@ConfigurationProperties(prefix = "jdbc")
//@Data
//public class JdbcProperties {
//    private String  username;
//    private String password;
//    private String url;
//    private String driverClassName;
//}
package com.chinasoft.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.JdbcProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


@Configuration//声明一个类是java声明类,配置类相当于xml
//@EnableConfigurationProperties(JdbcProperties.class)//声明激活属性类
public class JdbcConfig {
   // @Autowired
    //private JdbcProperties jdbc;
    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
      DruidDataSource dataSource = new DruidDataSource();
        //DataSource source = new DataSource();
        // dataSource.setUrl(jdbc.getUrl());
      //  dataSource.setDriverClassName(jdbc.getDriverClassName());
      //  dataSource.setUsername(jdbc.getUsername());
      //  dataSource.setPassword(jdbc.getPassword());
        return dataSource;
    }
}

在项目中我们使用阿里巴巴的DruidDataSource

六. DruidDataSource

DRUID 数据源概述 1、Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP、PROXOOL 等 DB 池的优点,同时加入了日志监控

2、Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池

3、《Spring Boot 默认数据源 HikariDataSource 与 JdbcTemplate》中已经介绍 Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源

4、本文承接《Spring Boot 默认数据源 HikariDataSource 与 JdbcTemplate》,重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控

com.alibaba.druid.pool.DruidDataSource 基本配置参数 配置 缺省值 说明 name 配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分开来。 如果没有配置,将会生成一个名字,格式是:"DataSource-" + System.identityHashCode(this) jdbcUrl 连接数据库的url,不同数据库不一样。例如: mysql : jdbc:mysql://10.20.153.104:3306/druid2 oracle : jdbc:oracle:thin:@10.20.149.85:1521:ocnauto username 连接数据库的用户名 password 连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter。详细看这里:https://github.com/alibaba/druid/wiki/%E4%BD%BF%E7%94%A8ConfigFilter driverClassName 根据url自动识别 这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName(建议配置下) initialSize 0 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 maxActive 8 最大连接池数量 maxIdle 8 已经不再使用,配置了也没效果 minIdle 最小连接池数量 maxWait 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。 poolPreparedStatements false 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 maxOpenPreparedStatements -1 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100 validationQuery 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。 testOnBorrow true 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 testOnReturn false 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 testWhileIdle false 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 timeBetweenEvictionRunsMillis 有两个含义: 1) Destroy线程会检测连接的间隔时间2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明 numTestsPerEvictionRun 不再使用,一个DruidDataSource只支持一个EvictionRun minEvictableIdleTimeMillis connectionInitSqls 物理连接初始化的时候执行的sql exceptionSorter 根据dbType自动识别 当数据库抛出一些不可恢复的异常时,抛弃连接 filters 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall proxyFilters 类型是List<com.alibaba.druid.filter.Filter>,如果同时配置了filters和proxyFilters,是组合关系,并非替换关系

<!--阿里Druid数据源引入项目即可--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency>

七.springboot项目SSM整合

新建一个Spring Initializr项目

创建项目的文件结构以及jdk的版本

选择项目所需要的依赖

修改项目名,finish完成

来看下建好后的pom <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
 
<name>demo</name>
<description>Demo project for Spring Boot</description>
 
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.5.RELEASE</version>
	<relativePath/> <!-- lookup parent from repository -->
</parent>
 
<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
</properties>
 
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>1.3.2</version>
	</dependency>
 
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>
 
<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

</project> 修改配置文件 本文不使用application.properties文件 而使用更加简洁的application.yml文件。将resource文件夹下原有的application.properties文件删除,创建application.yml配置文件(备注:其实SpringBoot底层会把application.yml文件解析为application.properties),本文创建了两个yml文件(application.yml和application-dev.yml),分别来看一下内容

application.yml

spring: profiles: active: dev application-dev.yml

server: port: 8080

spring: datasource: username: root password: 1234 url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.jdbc.Driver

mybatis: mapper-locations: classpath:mapping/*Mapper.xml type-aliases-package: com.example.entity

#showSql logging: level: com: example: mapper : debug 两个文件的意思是:

在项目中配置多套环境的配置方法。 因为现在一个项目有好多环境,开发环境,测试环境,准生产环境,生产环境,每个环境的参数不同,所以我们就可以把每个环境的参数配置到yml文件中,这样在想用哪个环境的时候只需要在主配置文件中将用的配置文件写上就行如application.yml

笔记:在Spring Boot中多环境配置文件名需要满足application-{profile}.yml的格式,其中{profile}对应你的环境标识,比如:

application-dev.yml:开发环境 application-test.yml:测试环境 application-prod.yml:生产环境 至于哪个具体的配置文件会被加载,需要在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

还有配置文件中最好不要有中文注释,会报错。

解决方法(未测试):spring boot application.yml文件中文注释乱码

接下来把启动文件移到com.example下,而且springboot的启动类不能放在java目录下!!!必须要个包将它包进去

否则会报错误:

Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package. 这个原因值得注意就是因为有时候很难在IDEA中的项目目录认出来这个错误并且还容易扫描不到一些类,传送门:SpringBoot扫描不到controller

然后开始创建实体类实现业务流程 创建包controller、entity、mapper、service。resources下创建mapping文件夹,用于写sql语句,也可以用注解的方式直接写在mapper文件里。下面直接贴代码

数据库表结构(之前小项目的表,直接拿来用)

CREATE TABLE user ( id int(32) NOT NULL AUTO_INCREMENT, userName varchar(32) NOT NULL, passWord varchar(50) NOT NULL, realName varchar(32) DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

entity.java

package com.example.entity;

/**

  • @Author:wjup

  • @Date: 2018/9/26 0026

  • @Time: 14:39 */ public class User { private Integer id; private String userName; private String passWord; private String realName;

    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 String getRealName() { return realName; }

    public void setRealName(String realName) { this.realName = realName; }

    @Override public String toString() { return "User{" + "id=" + id + ", userName='" + userName + ''' + ", passWord='" + passWord + ''' + ", realName='" + realName + ''' + '}'; } } UserController.java

package com.example.controller;

import com.example.entity.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

/**

  • @Author:wjup

  • @Date: 2018/9/26 0026

  • @Time: 14:42 */

@RestController @RequestMapping("/testBoot") public class UserController {

@Autowired
private UserService userService;
 
@RequestMapping("getUser/{id}")
public String GetUser(@PathVariable int id){
    return userService.Sel(id).toString();
}

} UserService.java

package com.example.service;

import com.example.entity.User; import com.example.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

/**

  • @Author:wjup

  • @Date: 2018/9/26 0026

  • @Time: 15:23 */ @Service public class UserService { @Autowired UserMapper userMapper; public User Sel(int id){ return userMapper.Sel(id); } } UserMapper.java

package com.example.mapper;

import com.example.entity.User; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository;

/**

  • @Author:wjup

  • @Date: 2018/9/26 0026

  • @Time: 15:20 */ @Repository public interface UserMapper {

    User Sel(int id); } UserMapping.xml

<?xml version="1.0" encoding="UTF-8"?>

​​

<resultMap id="BaseResultMap" type="com.example.entity.User">
    <result column="id" jdbcType="INTEGER" property="id" />
    <result column="userName" jdbcType="VARCHAR" property="userName" />
    <result column="passWord" jdbcType="VARCHAR" property="passWord" />
    <result column="realName" jdbcType="VARCHAR" property="realName" />
</resultMap>
 
<select id="Sel" resultType="com.example.entity.User">
    select * from user where id = #{id}
</select>

</mapper> 最终框架结构

完成以上,下面在启动类里加上注解用于给出需要扫描的mapper文件路径@MapperScan("com.example.mapper") package com.example;

import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.example.mapper") //扫描的mapper @SpringBootApplication public class DemoApplication {

public static void main(String[] args) {
	SpringApplication.run(DemoApplication.class, args);
}

} 最后启动,浏览器输入地址看看吧:http://localhost:8080/testBoot/getUser/1

测试成功,就这样基本框架就搭建成功了

最后给个番外篇如何更改启动时显示的字符拼成的字母,就是更改下图标红框的地方

其实很好改,只需要在resources下新建一个txt文件就可以,命名为banner.txt,那这种字符该怎么拼出来呢,下面推荐一个网址,有这种工具,链接传送门:字母转字符。如下:

直接输入要生成的字母,系统会自动转换,然后复制下面转换好的字符到新建的banner.txt文件中,重新启动项目就可以了。

八. 页面整合freemarker

本文知识点:

springboot如何集成freemarker模板引擎 添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>

配置属性文件

是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名模型属性。

spring.freemarker.allow-request-override=false

是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性。

spring.freemarker.allow-session-override=false

是否启用模板缓存。

spring.freemarker.cache=false

模板编码。

spring.freemarker.charset=UTF-8

是否检查模板位置是否存在。

spring.freemarker.check-template-location=true

Content-Type value.

spring.freemarker.content-type=text/html

是否启用freemarker

spring.freemarker.enabled=true

设定所有request的属性在merge到模板的时候,是否要都添加到model中.

spring.freemarker.expose-request-attributes=false

是否在merge模板的时候,将HttpSession属性都添加到model中

spring.freemarker.expose-session-attributes=false

设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用

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

是否优先从文件系统加载template,以支持热加载,默认为true

spring.freemarker.prefer-file-system-access=true

设定模板的后缀.

spring.freemarker.suffix=.ftl

设定模板的加载路径,多个以逗号分隔,默认:

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

设定FreeMarker keys.

spring.freemarker.settings.template_update_delay=0 spring.freemarker.settings.default_encoding=UTF-8 spring.freemarker.settings.classic_compatible=true

classic_compartible主要是进行是数据如果没有就会报错,页面解析用的

编写Controller @Controller public class FreemarkController {

@RequestMapping("/")
public String index(Model model) {
    return "index";
}

}

页面

Hello boy,

当前时间:${.now?string("yyyy-MM-dd HH:mm:ss.sss")}

1 2 3 4 5 6 7 8 9 10 11 常用的freemarker语法 下面详细介绍在ftl模板中如何使用列表、map、字符串、数字、日期、switch以及macro宏指令等语法。​

修改下controller,传递一些需要处理的参数

@RequestMapping("/") public String index(Model model) { Map map = new LinkedHashMap<>(); for (int i = 0; i < 5; i++) { map.put("key" + i, "value" + i); } model.addAttribute("list", Arrays.asList("string1", "string2", "string3", "string4", "string5", "string6")); model.addAttribute("map", map); model.addAttribute("name", " htTps://wWw.zHyD.mE "); model.addAttribute("htmlText", "<span style="color: red;font-size: 16px;">html内容</span>"); model.addAttribute("num", 123.012); model.addAttribute("null", null); model.addAttribute("dateObj", new Date()); model.addAttribute("bol", true); return "index"; }

重写index.ftl

当前时间:${.now?string("yyyy-MM-dd HH:mm:ss.sss")}

list长度:${list?size}

列表

<#list list as item>

${item }, 索引:${item_index },hasNext:${item_has_next}

<dt>数字遍历</dt>
    <#list 1..3 as item>
        <dd>数字${item}</dd>
    </#list>

<dt>map</dt>
    <#list map?keys as key>
        <dd>${map[key]}, 索引:${key_index },hasNext:${key_has_next}</dd>
    </#list>

</dl>

字符串

普通字符串:${name}

非html编码:${htmlText}

html编码:${htmlText?html}

首字母大写:${name?cap_first}

首字母小写:${name?uncap_first}

全小写:${name?lower_case}

全大写:${name?upper_case}

去除首位空格:${name?trim}

空字符串:${null?if_exists}

是否包含某个字符串:${name?contains("wWw")?string}

默认值:${null?default("空值默认")}

“${name}”字符串长度:${name?length}

定义字符串:str=码一码<#assign str="码一码"/>

字符串拼接(1):${"字符串拼接 + " + str}

字符串拼接(2):${"字符串拼接 + ${str}"}

字符串截取单个字符(1):${str[1]}

字符串截取(2):${str?substring(1)}

字符串截取(3):${str?substring(1,2)}

indexOf:${str?index_of("一")}

split分割字符串: <#list "a|b|c"?split("|") as item> ${item}

if...elseif...else: <#if null == ''> 匹配if显示 <#elseif null == '1'> 匹配elseif显示 <#else> 匹配else显示

​​

switch

<#switch str> <#case "你好"> 匹配“你好” <#break > <#case "码一码"> 匹配“码一码” <#break > <#default> 默认匹配

​​

数字

普通数字:${num}

数字类型:${num?string.number}

货币类型:${num?string.currency}

百分比类型:${num?string.percent}

格式化数字:${num?string("#.###")}

取数字的整数部分:${num?int}

​​

运算符

不等于:!= 例如:${(1 != 2)?string('1 != 2', '1 == 2')}

等于:== 例如:${(1 == 1)?string('1 == 1', '1 != 1')}

大于(1):> 例如:${(2 > 1)?string('2 > 1', '2 < 1')}。注:使用> 时必须加括号,否则可能会被当成普通的标签闭合符号而引起报错

大于(2):gt 例如:${(2 gt 1)?string('2 gt 1', '2 lte 1')}

大于等于:gte 例如:${(2 gte 2)?string('2 gte 2', '2 lt 2')}

小于(1):< 例如:${(1 < 2)?string('1 < 2', '1 > 2')}。注:使用< 时必须加括号,否则可能会被当成普通的标签闭合符号而引起报错

小于(2):lt 例如:${(1 lt 2)?string('1 lt 2', '1 gte 2')}

小于等于:lte 例如:${(2 lte 2)?string('2 lte 2', '2 gt 2')}

​​

boolean

普通boolean输出:${bol}

boolean判断输出:${bol?string('true的时候显示','false的时候显示')}

​​

日期

${dateObj?date}

${dateObj?time}

${dateObj?string("yyyy-MM-dd HH:mm:ss.SSS")}

​​

import

<#import "import.ftl" as importObj>

${importObj.importStr}

${importObj.importStr1}

​​

macro宏模板

<#macro listMacro title items>

${title?cap_first}:

  • <#list items as item>
  • ${item?cap_first}

<#nested >

<@listMacro items=["item1", "item2", "item3"] title="Items"> nested标签表示可以插入自定义的内容

include <#include "eclipse.ftl"> </body> </html>

九. springboot整合jsp

以下整合jsp使用的开发工具为intellij idea。其他开发工具目录结构相同

在pom.xml文件中加入注释部分的依赖

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
 
    <!-- 添加servlet依赖模块 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- 添加jstl标签库依赖模块 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    <!--添加tomcat依赖模块.-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
 
</dependencies>

其中最主要的,提供jsp引擎的就是

tomcat-embed-jasper这个依赖(一定要加) 然后修改配置文件中的Jsp文件访问路径(视图解析)

在application.properties文件中加入

spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp 配置完成后在webapp/WEB-INF/jsp文件夹下放jsp文件(必须有webapp/WEB-INF这个包,否则访问不到)

下面是我的项目目录

最后再建立一个控制器进行访问

@Controller public class IndexController { @RequestMapping("/index") public String index(){ return "index"; } } 访问结果如下,成功显示jsp页面

十. 注意事项(没有完全编译)

如果项目种没有完全编译,找到最上面的启动器在环境中进行编辑,选择绿色build旁边的小加号,然后输入指令clean compile,然后移动到build的上面去,这样每次一加载项目就会先clean在编译最后在运行。idea不像eclipse那样自动将新保存的文件或目录及其他资源更新到target目录中,必须在pom.xml中设置

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值