SpringBoot 总结

自己j觉得需要注意的地方,总结再次,大家可以参照

0、注意

a、放在 templates(模板引擎默认位置) 包下的页面访问不了

index.html 也访问不了

如果在 springboot 中配置了 thymeleaf 启动器,index.html 需要放在 static 才可以访问

b、SpringBoot 的测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {

    @Test
    public void contextLoads() {
    }

}
c、整合Mybatis

参考博客:https://blog.csdn.net/winter_chen001/article/details/77249029

数据源

配置数据源默认加载 Spring 的

spring:
  datasource:
    password: admindemo
    username: root
    url: jdbc:mysql://localhost:3306/test
    driver-class-name: com.mysql.jdbc.Driver
d、静态资源

static : css/ js /img

**templates:**存放模板引擎

##:**如果定义了 thymeleaf 引擎,访问跟目录只有在 static 下的index.html 才可访问得到

1、thymeleaf 使用

a-0

去掉默认的favicon.ico 图标

在配置文件中配置,后再 resource 的任意目录下加入:favicon.icon为名的图标即可

映射规则为:**/favicon.icon

#修改后,去掉默认的图标
spring.mvc.favicon.enabled=false
a、使用

需要引入 thymeleaf 的 xmlns

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

</html>
b、链接 和 action
<link rel="stylesheet" th:href="@{/asserts/css/dashboard.css}">
<form action="dashboard.html" th:action="@{/user/login}" method="post">
c、framgement 的使用

传递参数

当选择 "Dashboard“ 时激活,表示选择状态,当选择”员工列表“时,激活状态应该跳到”员工列表“

需要在 fragement 中传递参数

<!-- 表示接收参数 -->
<nav th:fragment="slide-nav(activeUri)" />

<!-- 使用传递过来的参数 -->
<a th:class="${activeUri == 'home' ? 'nav-link active' : 'nav-link'}"></a>
    
<a th:class="${activeUri=='list' ? 'nav-link active' : 'nav-link'} "></a>
d、th:if 的使用
<!--如果 user!=null ,该input就会显示,否则不会显示-->
<input type="hidden" name="id" th:if="${ user != null}">
e、三元运算符

下面两种语法是一样的

将 ? : 写在{} 里面和外面都行

th:text="${user==null ? '修改' : '添加'}"
th:text="${emp!=null} ? '修改' : '添加' "
g、使用 thymeleaf 的工具类
 <td th:text="${#dates.format( emp.birth, 'yyyy-MM-dd')}">birth</td>

2、SpringBoot 使用

a.关于拦截器
implements HandlerInterceptor 

如果没有登入成功,需要指定跳转的页面

httpServletRequest.getRequestDispatcher("/index.html").forward(httpServletRequest, httpServletResponse);
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("user");

        if( user!=null ){
            System.out.println("拦截");
            httpServletRequest.setAttribute("msg", "请先登入!");
            httpServletRequest.getRequestDispatcher("/index.html").forward(httpServletRequest, httpServletResponse);

            return true;
        }
        return false;
    }

    @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 {

    }
}
b、接管 spring mvc

在addViewControllers 方法中 增加视图映射,后天是填viewName,即是不用写 “前缀和后缀”

@Configuration
public class MyWebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

    // 加入一个 WebMvcConfigurerAdapter 的 bean
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){

        return new WebMvcConfigurerAdapter() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns(
                        "/index", "/index.html",
                        "/user/login", "/user/login.html"
                );
            }
        }
    }
}
c、防止表单重复提交

用户登入成功后,可以直接 重定向 到一个页面,这样就可以防止表单重复提交了(其中一种方法)


d、修改日期转换器默认的格式

在配置文件中配置

# 修改日期的转换器格式 
spring.mvc.date-format=yyyy-MM-dd

e、提交 restful 类型的表单

e、提交 restful 类型的表单
  • 页面创建一个post表单
  • 创建一个input项,name="_method";值就是我们指定的请求方式

可以把表单放在外面,防止对布局产生影响

<!--将删除的 post 表单放在外面,防止表单影响布局-->
<form id="deleteUserForm" method="post">
    <input type="hidden" name="_method" value="delete"/>
</form>
f、进行数据回显时需要判断数据是否为空
<div class="form-group">
   <select class="form-control" name="department.id">
         <!-- 数据来自 model -->
        <option th:each="dept : ${depts}" th:value="${dept.id}"   		          th:selected="${user!=null} ? ${dept.id} == ${user.id}" >
            1
        </option>
    </select>
</div>

关键代码: th:selected="${user!=null} ? ${dept.id} == ${user.id}

在进行取值 user.id 时需要判断是否 user!=null , 否则为空

" express ? 代码1 " 是thymeleaf 的特殊判断表达式

g、整合Mybatis

在线创建 SpringBoot 项目时,如果勾选了 Mybatis 选项,则默认是不会配置数据源,需要手动配置,如果直接运行会报错 : [Property ‘sqlSessionFactory’ or ‘sqlSessionTemplate’ are required]

如果没有勾选 Mybatis 选项,默认是有一个数据源的

注意上面如果勾选了,需要手动配置数据源

步骤:

  • 导入 maven 依赖
  • 配置数据源
  • 配置数据库的基本配置
  • 配置 mybatis 全局配置
  • 编写 Mapper 接口
  • 测试

maven 依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

配置数据源 和 全局配置

注意: @ConfigurationProperties(prefix=“spring.datasource”) 注解,会自动从全局配置文件(application.properties / application.yaml )文件中将数据库的配置项传过来

  • 返回一个 ConfigurationCustomizer 的 Bean 对象,会放到容器中作为 Mybatis 的全局配置文件
@Configuration
public class MyBatisConfig {

    /* 配置一个数据源 */
    @ConfigurationProperties(prefix="spring.datasource")
    @Bean
    public DataSource dataSource(){
        return new BasicDataSource();
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){

        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                // 表示开启驼峰命名法规则
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

Mapper 接口

用 @Mapper 声明注解一个 Mapper 接口

为了方便,可以在“启动类“中配置 Mapper 扫描包,就不用再每个 Mapper 接口中加上 @Mapper注解了

@Mapper
public interface UserMapper {

    @Select("select *from user where id=#{id}")
    public User getUser(Integer id);

    @Delete("delete from user where id=#{id}")
    public boolean delUser(Integer id);

    @Insert("insert into user(name,age) values (#{name}, #{age})")
    public boolean addUser(String name, Integer age);

}

测试类

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestMybatis {

    @Autowired
    UserMapper userMapper;

    @Test
    public void test1(){
        User user = userMapper.getUser(1);
        System.out.println(user);
    }
}

启动类中配置 Mapper 扫描包

// 扫描所有的 mapper
@MapperScan(value = "com.bigguy.cruddemo.mapper")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class CrudDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(CrudDemoApplication.class, args);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值