springboot进阶,分页插件 pageHelper,Swagger整合,日志

1,课程回顾

1,springboot 简化springboot搭建和使用过程框架
2,@SpringBootApplication 复合注解
@Configuration 相当于过去xml @Bean
@EnableAutoConfiguration 自动整合第三方jar
@ComponentScan 同包或者子孙包所有有spring标识的类,都会交给IOC容器管理 @Controller @RestController @Service @Repository @Component
3,SpringApplication.run() 初始化ApplicationContext 初始化监听器listener 初始化Runners 把要所有Runners排序,按顺序执行
4,springboot整合mybatis

2,本章重点

springboot 连接池(监控功能)
springboot 日志配置
springboot整合PageHelper
springboot整合swagger(postman)

3,具体内容

3.1 整合连接池

https://github.com/alibaba/druid
添加支持

  <!-- druid数据库连接池 -->
     <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.9</version>
     </dependency>
     如果是druid新版本,需要两个包:
       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

修改配置

#spring.datasource.druid.driver-class-name=oracle.jdbc.driver.OracleDriver  可配可不配,阿里的数据库连接池会通过url自动搜寻
spring.datasource.druid.url=jdbc:mysql://localhost:3306/db_qy141?useUnicode=true&characterEncoding=utf-8
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=10
spring.datasource.druid.max-wait=10
#是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。
#在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。
#spring.datasource.druid.pool-prepared-statements=true
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.time-between-eviction-runs-millis=60000
#配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.min-evictable-idle-time-millis=300000
#配置扩展插件:监控统计用的filter:stat  日志用的filter:log4j  防御sql注入的filter:wall
spring.datasource.druid.filters=stat,wall
#spring.datasource.druid.filter.stat.log-slow-sql=true
#spring.datasource.druid.filter.stat.slow-sql-millis=2000
# 合并多个DruidDataSource的监控数据
spring.datasource.druid.use-global-data-source-stat=true

监控配置:

   
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @ fileName:DruidConfig
 * @ description:
 * @ author:zhz
 * @ createTime:2021/7/14 20:33
 * @ version:1.0.0
 */
@Configuration
public class DruidConfig {
    /**
     *  主要实现WEB监控的配置处理
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        // 现在要进行druid监控的配置处理操作
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                new StatViewServlet(), "/druid/*");
        // 白名单,多个用逗号分割, 如果allow没有配置或者为空,则允许所有访问
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1,192.168.1.110");
        // 黑名单,多个用逗号分割 (共同存在时,deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.120");
        // 控制台管理用户名
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        // 控制台管理密码
        servletRegistrationBean.addInitParameter("loginPassword", "tiger");
        // 是否可以重置数据源,禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean ;
    }

    /**
     *配置过滤器WebStatFilter完成所有url请求的统计
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
        filterRegistrationBean.setFilter(new WebStatFilter());
        //所有请求进行监控处理
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
        return filterRegistrationBean ;
    }

    /**
     * 加载druidDataSource
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

}

请求地址:

 http://127.0.0.1:9999/druid/login.html

3.2 springboot日志配置:

springboot日志地址:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.logging
常用日志介绍:

Log4j

是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、数据库等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
Log4j有7种不同的log级别,按照等级从低到高依次为:TRACE、DEBUG、INFO、WARN、ERROR、FATAL、OFF。如果配置为OFF级别,表示关闭log。
Log4j支持两种格式的配置文件:properties和xml。包含三个主要的组件:Logger、appender、Layout。
详细配置:
https://blog.csdn.net/yanweihpu/article/details/80090839

Log4j2

Spring Boot1.4以及之后的版本已经不支持log4j,log4j也很久没有更新了,现在已经有很多其他的日志框架对Log4j进行了改良,比如说SLF4J、Logback等
https://logging.apache.org/log4j/2.x/
详细配置:
https://blog.csdn.net/qq_41071876/article/details/105376862

SLF4J

SLF4J,即简单日志门面(Simple Logging Facade for Java),不是具体的日志解决方案,而是通过Facade Pattern提供一些Java logging API,它只服务于各种各样的日志系统。按照官方的说法,SLF4J是一个用于日志系统的简单Facade,允许最终用户在部署其应用时使用其所希望的日志系统。
http://www.slf4j.org/

Logback

Logback,一个“可靠、通用、快速而又灵活的Java日志框架”,logback当前分成三个模块:logback-core,logback- classic和logback-access。logback-core是其它两个模块的基础模块。logback-classic是log4j的一个改良版本。此外logback-classic完整实现SLF4J API使你可以很方便地更换成其它日志系统如log4j或JDK Logging。
http://logback.qos.ch/
springboot默认使用了logback配置.

Apache Commons Logging

Apache Commons Logging ,之前叫 Jakarta Commons Logging(JCL)提供的是一个日志(Log)接口(interface),同时兼顾轻量级和不依赖于具体的日志实现工具。它提供给中间件/日志工具开发者一个简单的日志操作抽象,允许程序开发人员使用不同的具体日志实现工具。用户被假定已熟悉某种日志实现工具的更高级别的细节。JCL提供的接口,对其它一些日志工具,包括Log4J, Avalon LogKit, and JDK 1.4+等,进行了简单的包装,此接口更接近于Log4J和LogKit的实现。
https://commons.apache.org/proper/commons-logging/guide.html

springboot项目类中日志使用

 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 private   Logger log = LoggerFactory.getLogger(DeptController.class);

springboot在properties直接配置日志:

#日志相关配置
#配置日志文件的路径
logging.file.path=d:/springboot-log
#配置日志文件名,如果该属性不配置,默认文件名为spring.log    windows下:path和name不可以同时配置,通知配置只有name起效
#logging.file.name=cc.log
#配置日志级别
logging.level.root=info
#定制控制台日志输出格式
    #%d{HH:mm:ss.SSS}——日志输出时间
    #%thread——输出日志的进程名字,这在Web应用以及异步任务处理中很有用
    #%-5level——日志级别,并且使用5个字符靠左对齐
    #%logger- ——日志输出者的名字
    #%msg——日志消息
    #%n——平台的换行符
logging.pattern.console=%d{yyyy/MM/dd} [%thread] %-5level %logger- %msg%n 
#定制文件日志输出格式
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n
#mybatis配置日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

springboot的logback配置

配置日志不需要导入jar,日志包在父项目中已经引入,具体位置如下:
spring-boot-starter-parent ----父包—> spring-boot-dependencies ----父包—>spring-boot-dependencies -----查找----> spring-boot-starter-logging —点击进去----> 能看到日志包:logback-classic,log4j-to-slf4j…

在resources下创建logback.xml或者logback-spring.xml,复制配置进去

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <property name="LOG_HOME" value="D:/projects/log" />
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 按照每天生成日志文件 -->
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/springbootdemo.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
 
 
    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="DEBUG"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>
 
    <!-- 日志输出级别
      trace<debug<info<warn<error<fatal
    级别之间是包含的关系,意思是如果你设置日志级别是trace,则大于等于这个级别的日志都会输出。
    trace: 是追踪,就是程序推进以下,你就可以写个trace输出,所以trace应该会特别多,不过没关系,我们可以设置最低日志级别不让他输出。
    debug: 调试么,我一般就只用这个作为最低级别,trace压根不用。是在没办法就用eclipse或者idea的debug功能就好了么。
    info: 输出一下你感兴趣的或者重要的信息,这个用的最多了。
    warn: 有些信息不是错误信息,但是也要给程序员的一些提示,类似于eclipse中代码的验证不是有error 和warn(不算错误但是也请注意,比如以下depressed的方法)。
    error: 错误信息。用的也比较多。
    fatal: 级别比较高了。重大错误,这种级别你可以直接停止程序了,是不应该出现的错误么!不用那么紧张,其实就是一个程度的问题。
   -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
    <!--日志异步到数据库 -->
    <!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
    <!--<!–日志异步到数据库 –>-->
    <!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
    <!--<!–连接池 –>-->
    <!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
    <!--<driverClass>com.mysql.jdbc.Driver</driverClass>-->
    <!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>-->
    <!--<user>root</user>-->
    <!--<password>root</password>-->
    <!--</dataSource>-->
    <!--</connectionSource>-->
    <!--</appender>-->
</configuration>

3.3 springboot整合shiro

springboot 的application.properties配置
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
springboot访问templates配置(或者创建resources放置HTML)
spring.resources.static-locations=classpath:/templates/
整合前需要先讲解讲解@Configuration和@Bean用法,否则整合代码看不懂。

@Configuration 可理解为用spring的时候xml里面的标签,注解标记在类上,就像之前我们声明的一个spring的xml配置文件,该类我们称为配置类.
@Bean 可理解为用spring的时候xml里面的标签,标记在方法之上,方法的返回值为向springIOC容器之中注入一个Bean.其中,返回值相当于xml文件bean标签的class属性.如果@Bean配置value相当于id属性,如果没有配置,方法的名称相当于id属性

package com.aaa.sbms.config;

import com.aaa.sbms.entity.Dept;
import com.aaa.sbms.entity.Emp;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * fileName:MyConfig
 * description:
 * author:zz
 * createTime:2019/11/26 15:48
 * version:1.0.0
 */
@Configuration
public class MyConfig {

    /**
     * 相当于过去的
     *  <bean name="emp"   class="com.aaa.sbms.entity.Emp"  >
     * @return
     */
    @Bean
    public Emp emp(@Qualifier("d1") Dept d){
        Emp emp = new Emp();
        emp.setEname("zhangsan");
        emp.setSal(10000);
        emp.setDept(d);
        return emp;
    }

    @Bean("d1")
    public Dept dept(){
        Dept dept =new Dept();
        dept.setDname("kaifa1");
        dept.setLoc("1lou");
        return dept;
    }
}
package com.aaa.sbms;

import com.aaa.sbms.entity.Emp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@MapperScan("com.aaa.sbms.dao")
@EnableTransactionManagement  //开启注解式事务
public class SbmShiroApplication {

	public static void main(String[] args) {
		ConfigurableApplicationContext applicationContext = SpringApplication.run(SbmShiroApplication.class, args);
		Emp emp =(Emp)applicationContext.getBean("emp");
		System.out.println(emp.getEname()+","+emp.getSal());
		System.out.println(emp.getDept().getDname()+","+emp.getDept().getLoc());
	}

}

上面知识点熟悉后,整合shiro
1,引入包:

                          <dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-core</artifactId>
  <version>1.4.0</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-ehcache</artifactId>
  <version>1.4.0</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring</artifactId>
  <version>1.4.0</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-web</artifactId>
  <version>1.4.0</version>
</dependency>

或者使用:

 <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.7.1</version>
    </dependency>

2,编写ShiroConfig

package com.aaa.sbm.configuration;

import com.aaa.sbm.util.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * fileName:ShiroConfiguration
 * description:
 * author:zz
 * createTime:2020/10/13 10:39
 * version:1.0.0
 */
@Configuration  // 相当于spring-shiro-config.xml
public class ShiroConfiguration {

    /**
     * shiro过滤器工厂实例  配置拦截到所有请求进行处理
     * @return
     */
    @Bean // <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    public ShiroFilterFactoryBean shiroFilter(){
        //实例化对象
         ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
         //让securityManager生效
         shiroFilterFactoryBean.setSecurityManager(securityManager());
         //设置未认证跳转的登录路径
        shiroFilterFactoryBean.setLoginUrl("/html/login.html");
        //定义放开或者拦截的请求路径
        Map<String, String> urlMap = new LinkedHashMap<>(); //按照添加的先后顺序
        //免过滤地址
        urlMap.put("/css/**","anon");
        urlMap.put("/js/**","anon");
        urlMap.put("/images/**","anon");
        urlMap.put("/html/login.html","anon");
        urlMap.put("/html/register.html","anon");
        urlMap.put("/user/login","anon");
        urlMap.put("/user/register","anon");
        //注销
        urlMap.put("/logout","logout");
        //过滤地址
        urlMap.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(urlMap);
         return shiroFilterFactoryBean;
    }


    /**
     * 实例化SecurityManager
     * @return
     */
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager =new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm());
        return  securityManager;
    }


    /**
     *实例化自定义Realm类
     * @return
     */
    @Bean
    public MyRealm myRealm(){
        MyRealm myRealm =new MyRealm();
        //设值算法类
        myRealm.setCredentialsMatcher(credentialsMatcher());
        return myRealm;
    }

    /**
     *实例化加密算法类
     * @return
     */
    @Bean
    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设值加密算法名称
        hashedCredentialsMatcher.setHashAlgorithmName("SHA-512");
        //设置hash次数
        hashedCredentialsMatcher.setHashIterations(1024);
           return hashedCredentialsMatcher;
    }

   /**
     * 主要实现的功能为使用bean后处理器的回调函数,根据ioc容器配置的advisor,来对ioc 容器中的其他bean生成相应代理
     * @return
     */
    @Bean
    @ConditionalOnMissingBean  //保证该 bean在底层注册一次
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

    /**
     * 方法层面的权限过滤,用于支持shiro注解,配置后shiro识别@RequiresPermissions
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}

3.myrealm

package com.aaa.sm.config;

import com.aaa.sm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * fileName:MyShiroRealm
 * description:
 * author:zz
 * createTime:2019/11/14 10:38
 * version:1.0.0
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : user.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (Permissions permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        Object userName = authenticationToken.getPrincipal();
        Map map = new HashMap();
        map.put("userName",userName);
        //根据用户名查询列表
        List<Map> userMapList = userService.getListByParam(map);
        //判断
        if(userMapList!=null&&userMapList.size()>0){
            Map userMap = userMapList.get(0);
            //SecurityUtils.getSubject().getSession().setAttribute("userInfo",userMap);
            return new SimpleAuthenticationInfo(userMap.get("USER_NAME")+"",
                    userMap.get("PASSWORD")+"",getName());
        }else {
            throw new AccountException();
        }
    }
}

方法配置:

@RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "admin success!";
    }

    @RequiresPermissions("query")
    @GetMapping("/index")
    public String index() {
        return "index success!";
    }

    @RequiresPermissions("add")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }

4,编写登录页面和功能,进行测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
    <script src="/js/jquery-3.4.1.min.js"></script>
    <script>
        $(function () {
            //绑定登录按钮点击事件
            $("#btn").click(function () {
                $.ajax({
                    url:"/user/login",
                    data:{userName:$("#userN").val(),passWord:$("#passW").val()},
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        alert(data);
                        alert(data=='1');
                       if(data=='1'){
                           alert(222);
                           //跳转首页
                          location.href="/html/index.html";
                       }else{
                           $("#errorDiv").html("用户名或者密码错误!");
                       }
                    },
                    error:function () {
                        alert("error");
                    }
                });
            });
        });
    </script>
</head>
<body>
     <div style="color: red;" id="errorDiv"></div>
     用户名:<input type="text" id="userN">
     密码:<input type="text" id="passW">
         <input type="button" id="btn" value="登录">
</body>
</html>

3.4 mybatis分页插件 pageHelper

https://pagehelper.github.io/
https://gitee.com/free/Mybatis_PageHelper

1,添加jar包

   <!-- 分页插件pagehelper -->       
   <dependency>  
          <groupId>com.github.pagehelper</groupId>      
      <artifactId>pagehelper-spring-boot-starter</artifactId>
         <version>1.3.0</version>       
 </dependency>     
 <!-- 分页插件pagehelper -->

2,添加springboot配置

https://github.com/abel533/MyBatis-Spring-Boot

 #分页插件
#helperDialect属性来指定分页插件使用哪种方言
pagehelper.helper-dialect=oracle
#当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。
pagehelper.reasonable=true
#支持通过 Mapper 接口参数来传递分页参数,默认值false,分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,查找到合适的值时就会自动分页。
pagehelper.support-methods-arguments=true
#增加了该参数来配置参数映射,用于从对象中根据属性名取值
pagehelper.params=count=countSql

3,具体使用
与以前controller区别

//设置当前第几页和每页显示数量 PageHelper.startPage(Integer.valueOf(map.get(“pageNo”)+""),Integer.valueOf(map.get(“pageSize”)+""));
//用PageInfo对结果进行包装
PageInfo pageInfo =new PageInfo(newsService.getList());

/**
     * 分页部门查询
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping("page")
    public Object page(@RequestParam Map map){
        int pageNo = Integer.valueOf(map.get("pageNo")+"");
        int pageSize = Integer.valueOf(map.get("pageSize")+"");
        //初始化配置
        PageHelper.startPage(pageNo,pageSize);
        PageInfo<Map> pageInfo = new PageInfo<Map>(deptService.getList());
       //如果使用easyui可以这样封装,其他框架,自己根据pageInfo解析
        Map tmap  = new HashMap();
        tmap.put("total",pageInfo.getTotal());
        tmap.put("rows",pageInfo.getList());
        return tmap;
    }

3.5 springboot整合thymeleaf (类似jsp模板)

https://www.thymeleaf.org/
Thymeleaf是适用于Web和独立环境的现代服务器端Java模板引擎。
Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板-HTML可以在浏览器中正确显示,也可以作为静态原型工作,从而可以在开发团队中加强协作。
Thymeleaf拥有用于Spring Framework的模块,与您喜欢的工具的大量集成以及插入您自己的功能的能力,对于现代HTML5 JVM Web开发而言,Thymeleaf是理想的选择-尽管它还有很多工作要做。
3.5.1 引入jar:

 <!-- thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.5.2 application.properties添加配置

# thymeleaf
#配置thymeleaf模板所在的位置
spring.thymeleaf.prefix=classpath:/templates/
#配置thymeleaf模板后缀
spring.thymeleaf.suffix=.html
#配置thymeleaf文档的编码
spring.thymeleaf.encoding=utf-8
#内容类型
spring.thymeleaf.content-type=text/html
#模板格式
spring.thymeleaf.mode=HTML
#cache这一行是将页面的缓存关闭,不然我们改变页面之后可能不能及时看到更改的内容,默认是true
spring.thymeleaf.cache=false

3.5.3 后台绑定值

               org.springframework.ui.Model   + String 
                或者
               org.springframework.web.servlet.ModelAndView

3.5.4 页面thymeleaf标签的使用

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#reformatting-dates-in-our-home-page
引入:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
	     标签:
	           <tr th:each="dept:${deptList}">
	           <td th:text="${dept.deptNo}"> </td>
	          <a th:href="@{/deptTh/toUpdate(deptNo=${dept.deptNo})}">修改</a>
	          <a th:href="'javascript:del('+${dept.deptNo}+')'">删除</a>
	          <input type="hidden" name="deptNo" value="deptNo" th:value="${dept.deptNo}"/>
	   <input type="text" name="dname"   th:value="${dept.dname}"  >

3.6 springboot整合swagger

简介:
借助Swagger开源和专业工具集,为用户,团队和企业简化API开发。了解Swagger如何帮助您大规模设计和记录API。
Swagger工具的强大功能始于OpenAPI规范— RESTful API设计的行业标准
特点:
开源 免费,专业
使用:
1,jar依赖

  <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

2,springboot整合swagger配置

    package com.aaa.sbm.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * fileName:SwaggerConfig
 * description:
 * author:zz
 * createTime:2020/1/11 14:50
 * version:1.0.0
 */
@Configuration
public class SwaggerConfig {

    /**
     * 创建一个docket
     * @return
     */
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //.enable(false)  //swagger不能访问
                .select()
                //配置要扫描接口的方式
                .apis(RequestHandlerSelectors.basePackage("com.aaa.sbm.controller"))
                //路径过滤
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * apiInfo
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多请关注http://www.baidu.com")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact("aaa")
                .version("1.0")
                .build();
    }
}

3,开启swagger
@EnableSwagger2
4, 可选配置

   方法:
     @ApiOperation("部门删除")
      参数:
      @ApiParam("部门删除参数")

5,测试
http://localhost:8888/swagger-ui.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杵意

谢谢金主打赏呀!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值