Spring Boot Web综合开发(filter过滤器、hikari数据库池、mybatis、thymeleaf模版)

1.Web开发涉及到很多内容,应新项目需要,开发了个小demo,供团队开发人员查阅。也写篇博客写给有需要的朋友们。

2.为什么用Spring Boot?它可以简单、快速的搭建一个Spring Web项目,使用很少的配置就可以运行项目,大大简化了以往Spring Mvc等项目中的各种文件配置工作。

3.文章使用到的有下面内容

  1. filter过滤器,用它来过滤请求。进行权限验证,日志记录等
  2. hikari数据库连接池,Java平台目前性能最好的连接池,高并发下也比较稳定,Spring Boot 2.0已内置为默认的连接池。然后也参考了阿里的 druid 连接池不过它侧重SQL监控,运维方面。性能吊打传统的C3P0连接池
  3. mybatis注解版,都说后台管理系统使用 hibernate,互联网项目使用 mybatis,我特意测试了下,发现使用Spring Boot Mybatis的注解版,发现非常方便,没有传统mybatis的xml配置和dao实现类
  4. thymeleaf模版,尽量避免使用JSP,thymeleaf可以让前端小伙伴查看静态页面效果,也可以让后端工程师查看动态内容,互不影响,协同工作。

4.使用IDEA 创建Maven项目,或者在 http://start.spring.io/ 网址中数据项目包名,生成Maven项目,再本地打开项目

5.项目添加filter过滤器,需要2个步骤:1.实现 Filter 接口和方法 , 2.将 @Configurationz 注解添加到类上,将自定义的Filter加入到过滤链

@Configuration
public class CookieFilter implements Filter {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CookieFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //过滤器逻辑实现,cookie、session权限验证
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        if (url.startsWith("/") && url.length() > 1) {
            url = url.substring(1);
        }
        logger.info("filter url:"+ url);
        Cookie[] cookies = httpRequest.getCookies();
        if(cookies == null){
            //cookie 不存在 跳转登录页
            httpResponse.sendRedirect("/");
            return;
        }else {
           //存在 
        }
    }

    @Override
    public void destroy() {

    }
}

6.hikari数据库连接池,仅仅需要在项目的 pom.xml 和 application.properties中进行配置即可(包含了MySql的连接配置)

<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>
    <version>8.0.11</version>
</dependency>
# jdbc_config   datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=15000
spring.datasource.username=test
spring.datasource.password=test

# Hikari will use the above plus the following to setup connection pooling
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=25
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1

启动项目后出现下面的 com.zaxxer.hikari.HikariDataSource : DatebookHikariCP - Starting…信息表示成功
这里写图片描述

7.Mybatis注解版的使用,1引用依赖,2.启动类中添加扫描注解,3.添加mapper接口类,里面写数据操作方法

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
@MapperScan("com.zypcy.datasource.HikariCP.mapper")
@SpringBootApplication
public class HikariCpApplication {
    .......
}
//@Mapper  在启动类上添加了扫描路径,可以不用单独在类上添加映射注解了
public interface UserMapper {
    //查询数据量
    @Select("select count(1) from user ")
    int getCount();

    /**
     * 根据userCode查询用户
     * 查询出的字段如果和实体类中的一一对应则不需要代码去对应 @Result(property = "userCode" , column = "user_code") ,我的实体类中没有下划线,数据表中有,就需要手动对应
     * @param userCode
     * @return
     */
    @Select("select * from user where user_code = #{userCode}")
    @Results({
            @Result(property = "userCode" , column = "user_code"),
            @Result(property = "contactNumber" , column = "contact_number"),
            @Result(property = "weixinNumber" , column = "weixin_number"),
            @Result(property = "qqNumber" , column = "qq_number"),
            @Result(property = "weixinImgHref" , column = "weixin_img_href")
    })
    User getUserById(String userCode);

    /**
     * 新增用户
     * @param user
     */
    @Insert("INSERT INTO user (user_code,contact_number,weixin_number,qq_number,weixin_img_href) VALUES (#{userCode},#{contactNumber},#{weixinNumber},#{qqNumber},#{weixinImgHref})")
    void insert(User user);

    /**
     * 修改用户
     * @param user
     */
    @Update("update user set contact_number=#{contactNumber},weixin_number=#{weixinNumber},qq_number=#{qqNumber},weixin_img_href=#{weixinImgHref} where user_code =#{userCode}")
    void update(User user);

    /**
     * 删除用户
     * @param userCode
     */
    @Delete("delete from user where user_code =#{userCode}")
    void delete(String userCode);

    /**
     * 分页查询  - 两个参数需要用 @Param ,否则会报错
     * @return
     */
    @Select("select * from user limit #{pageNo} , #{pageSize}")
    @Results({
            @Result(property = "userCode" , column = "user_code"),
            @Result(property = "contactNumber" , column = "contact_number"),
            @Result(property = "weixinNumber" , column = "weixin_number"),
            @Result(property = "qqNumber" , column = "qq_number"),
            @Result(property = "weixinImgHref" , column = "weixin_img_href")
    })
    List<User> findByPage(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize);

    /**
     * 多表联合查询
     */
    @Select("select suser.user_id,suser.user_code,suser.user_name,otheruser.contact_number from sys_user suser INNER JOIN user otheruser on suser.user_code = otheruser.user_code where otheruser.user_code=#{userCode}")
    UserDto getUserByUserCode(String userCode);
}

注解版 Mybatis 的代码全部搞定,只要写mapper接口类,不需要写老版本中的mapper.xml配置、Dao类的实现等一大堆东西,非常适合快速开发。Now , 测试类中,注入 UserMapper 进行测试 (JSON引用的阿里的fastjson)

@Test
public void testQuery(){
    User user = userService.getUserById("administrator");
    System.out.println(JSON.toJSON(user));
}

测试成功 - 查询出数据:
这里写图片描述

8.thymeleaf模版的作用上面已经说明了,下面引入依赖,在项目中添加控制器,在resources - templates目录下添加 index.html 模版页面,thymeleaf有缓存,在开发时需要去掉缓存,只需在application.properties中加入:spring.thymeleaf.cache=false

<!--Spring MVC必须-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
@Controller
public class IndexController {

    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("name","hello world"); //返回到页面上的数据
        return "index"; //返回resources - templates下的index.html页面
    }
}
//index.html code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
</head>
<body>
    <!--在div中展示 name 属性值-->
    <div th:text="${name}"></div>
</body>
</html>

运行项目可以看到 hello world
这里写图片描述

Spring Boot可通过Maven工具把项目打成 jar 包,然后通过 java -jar xx.jar 运行。内置了tomcat,可以直接运行,不依赖tomcat部署
项目demo下载地址:HikariCP-Demo 没有积分的发私信告诉我邮箱。看到后发源码过去。

猜你喜欢

转载自blog.csdn.net/zhuyu19911016520/article/details/80255043