SpringBoot

本文介绍了如何使用SpringBoot快速搭建Web项目,并整合Mybatis和Mybatis Plus进行数据操作。内容包括配置application.yaml和properties文件、创建Mapper接口和实体类、使用Thymeleaf模板引擎进行页面渲染、实现分页查询以及设置登录拦截器。此外,还讲解了处理404错误的方法。
摘要由CSDN通过智能技术生成

SpringBoot

1.快速入门(注意 mybatis的版本号 用5.XXX的)

一.创建web项目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vQ65TV9W-1646101175847)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211122132532101.png)]

二.

2.application.yaml

server:
  # 服务器的HTTP端口,默认为8080
  port: 8080
  servlet:
    # 应用的访问路径
    context-path: /
  tomcat:
    # tomcat的URI编码
    uri-encoding: UTF-8
    # tomcat最大线程数,默认为200
    max-threads: 800
    # Tomcat启动初始化的线程数,默认值25
    min-spare-threads: 30

spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    username: root
    password: root

mybatis:
  # 搜索指定包别名
  typeAliasesPackage: com.demo.**.entity
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapperLocations: classpath*:mybatis/*Mapper.xml




3.application.properties

spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url= jdbc:mysql://localhost:3306/account
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#整合
#mybatis.type-aliases-package=com.demo.entity
#mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#可以把 POST 请求转为 DELETE 或 POST 请求
spring.mvc.hiddenmethod.filter.enabled=true

小彩蛋banner.txt


//                          _ooOoo_                               //
//                         o8888888o                              //
//                         88" . "88                              //
//                         (| ^_^ |)                              //
//                         O\  =  /O                              //
//                      ____/`---'\____                           //
//                    .'  \\|     |//  `.                         //
//                   /  \\|||  :  |||//  \                        //
//                  /  _||||| -:- |||||-  \                       //
//                  |   | \\\  -  /// |   |                       //
//                  | \_|  ''\---/''  |   |                       //
//                  \  .-\__  `-`  ___/-. /                       //
//                ___`. .'  /--.--\  `. . ___                     //
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
//      ========`-.____`-.___\_____/___.-`____.-'========         //
//                           `=---='                              //
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//            佛祖保佑       永不宕机     永无BUG                    //

springboot整合mybatis/Plus

1.导包

<!--springboot整合mybatis 用了这个包 就不需要用mybatis的包了-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>
<!--连接驱动的包 注意自己的版本号 我的mysql是5  所以使用的版本要改成5.XX.XX-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.10</version>
</dependency>
 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2.创建mapper类和users实体类

这个是不需要自己写配置文件 和sql代码的里面

package com.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.entity.users;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Mapper//这个是扫包的 or@MapperScan("com.demo.mapper")加到启动类上面
@Repository
public interface usersMapper extends BaseMapper<users> {


}

3.thymeleaf的快速入门

1.导入依赖
<!--导入html模板引擎-->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
2.引入thymeleaf的html头
<html lang="en" xmlns:th="http://www.thymeleaf.org">
3.将需要跳转的页面 通过controller

注意!!!html页面需要放在templates目录下才可以被访问到

@RequestMapping("/queryall")
public String queryall(){
    List<users> queryall = usersService.queryall();
    System.out.println(queryall);
    return "hehe";
}
4.config配置(webMVCconfig)
@Configurationpublic class myMVCconfig implements WebMvcConfigurer {    @Override    public void addViewControllers(ViewControllerRegistry registry) {        registry.addViewController("/hehe.html").setViewName("hehe");        registry.addViewController("/login.html").setViewName("login");        registry.addViewController("/").setViewName("login");        registry.addViewController("/index.html").setViewName("index");        registry.addViewController("/moduleSetting.html").setViewName("moduleSetting");        registry.addViewController("/user.html").setViewName("user");    }}

4.条件查询器wrapper

1.通过名字查询
@Test    //条件是否相同 通过名字查询column:列的字段  val:值void test2() {    QueryWrapper<users> wrapper=new QueryWrapper<>();    wrapper.eq("uname","lisi");    users users = usersMapper.selectOne(wrapper);    System.out.println(users);}
2.查询id在10-20之间的用户
@Test    //查询id在10-20之间的用户void test3() {    QueryWrapper<users> wrapper=new QueryWrapper<>();    wrapper.between("id","10","20");    List<users> list = usersMapper.selectList(wrapper);    System.out.println(list);}
3.模糊查询(notlike是不包含“tes”,like是包含)
@Test    //模糊查询void test4() {    QueryWrapper<users> wrapper=new QueryWrapper<>();    wrapper.notLike("uname","tes").like("uname","i");    List<Map<String, Object>> maps = usersMapper.selectMaps(wrapper);    System.out.println(maps);}

5.分页查询

1.config.MybatisPlusConfig
package com.demo.config;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration/*@MapperScan("com.demo.mapper.*")*/public class MybatisPlusConfig {    // 旧版    @Bean    public PaginationInterceptor paginationInterceptor() {        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();        return paginationInterceptor;    }}
2.controller
    @RequestMapping("/fy")    @ResponseBody    public String fy(){        Page<users> page=new Page<>(1,10);        IPage<users> fy = usersService.fy(page);       System.out.println(page.getTotal()+"======");        //page里面有很多 属性值 当前页 总页等等        System.out.println(fy);        return "hehe";    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZgRsQZwl-1646101175848)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211122182710339.png)]

3.service/impl
//servicepublic IPage<users> fy(Page page);//serviceimpl    @Override    public IPage<users> fy(Page page) {        return usersMapper.selectPage(page,null);    }
4.mapper
@Mapper@Repositorypublic interface usersMapper extends BaseMapper<users> {}

5.1.分页查询加页面版

1.config.MybatisPlusConfig
package com.demo.config;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration/*@MapperScan("com.demo.mapper.*")*/public class MybatisPlusConfig {    // 旧版    @Bean    public PaginationInterceptor paginationInterceptor() {        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();        return paginationInterceptor;    }}
2.controller
    @RequestMapping("/fy")    public String fy(Model model,                     @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,                     @RequestParam(value = "pageSize", defaultValue = "5") int pageSize){        Page<users> page=new Page<>(pageNum,pageSize);        IPage<users> fy = usersService.fy(page);        model.addAttribute("pagelist",page);        System.out.println(page.getRecords()+"====123");        return "user";    }//getRecords是list里面的数据

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QQtXjT6a-1646101175849)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211122182710339.png)]

3.service/impl
//servicepublic IPage<users> fy(Page page);//serviceimpl    @Override    public IPage<users> fy(Page page) {        return usersMapper.selectPage(page,null);    }
4.mapper
@Mapper@Repositorypublic interface usersMapper extends BaseMapper<users> {}
5.html页面
<table id="tbRecord">   <thead>      <tr>         <th>ID</th>         <th>姓名</th>         <th>用户名</th>         <th>邮箱</th>         <th>电话 </th>         <th>编辑</th>         <th>删除</th>      </tr>   </thead>   <tbody th:each="users:${pagelist.getRecords()}">           <td hidden id="uid" th:text="${users.getId()}"></td>         <td th:text="${users.getId()}">0</td>         <td th:text="${users.getUname()}">张三11</td>         <td th:text="${users.getAccountname()}"></td>         <td th:text="${users.getEmail()}">354545454@qq.com</td>         <td th:text="${users.getPhone()}">182333443434</td>         <td class="td_column_edit" id="td_column_edit_1" align="center" style="cursor:pointer;">            <button class="btn btn-primary" th:onclick="'javascript:update_users('+${users.getId()}+')'"><i class="icon-edit" style="margin-right:3px"></i>编辑</button></td>         <td class="td_column_delete" id="td_column_delete_1" align="center" style="cursor:pointer;">            <button class="btn btn-danger" th:onclick="'javascript:delete_users('+${users.getId()}+')'"><i class="icon-trash" style="margin-right:3px"></i>删除</button></td>      </tr>   </tbody><!--//页脚的页面--><div id="usersfy">    <ul class="pagination" >		<!--上一页-->        <li th:if="${pagelist.getCurrent()>=1}">            <a th:href="'/users/fy?pageNum='+${pagelist.getCurrent()-1}">&laquo;</a>        </li>        <!--中间的部分 i :${#numbers.sequence(1, pagelist.getPages())}这个表达式就是循环i的-->        <li th:each="i :${#numbers.sequence(1, pagelist.getPages())}">            <a th:href="'/users/fy?pageNum='+${i}"><span th:text="${i}"></span></a>        </li>        <!--下一页-->        <li th:if="${pagelist.getCurrent()<=pagelist.getPages()}" >            <a th:href="'/users/fy?pageNum='+${pagelist.getCurrent()+1}">&raquo;</a>        </li>    </ul></div></table>

原文:https://blog.csdn.net/weixin_38117760/article/details/103251403

5.404找不到页面的处理

1.导入依赖

<!--导入html依赖-->    <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-thymeleaf</artifactId>    </dependency>

2.添加此模板(thymeleaf的依赖)。会从templates中去找相对于的页面。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F2EEXObT-1646101175849)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211123210937485.png)]

@RequestMapping("/queryall")    public String queryall(){        List<users> queryall = usersService.queryall();        System.out.println(queryall);        return "hehe";    }

6.登录拦截器

1.config:loginHandlerInterceptor

//登录拦截器
public class loginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录成功获取session
        Object login_users = request.getSession().getAttribute("login_users");
        if(login_users!=null){
            return true;
        }else{
            request.setAttribute("msg","没有权限,请先登录");
            request.getRequestDispatcher("/login.html").forward(request,response);
            return false;
        }

    }

}

2.在webmcv中添加拦截器

@Configuration
public class myMVCconfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/hehe.html").setViewName("hehe");
        registry.addViewController("/login.html").setViewName("login");
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/moduleSetting.html").setViewName("moduleSetting");
        registry.addViewController("/user.html").setViewName("user");
        registry.addViewController("/users/fy").setViewName("user");

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new loginHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/index.html","/login.html","/css","/font","/images/**","/fonts","/layui","/users/login");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值