摘要:
该文为需要搭建SpringWeb项目学习的同学提供参考,其中会包括以下功能
1.使用Idea搭建SpringWeb项目初始环境
2.加入访问Html页面和静态资源
3.返回动态的Html页面处理
4.断言异常拦截处理以及自定义增加请求参数
5.引入logback日志记录(日志记录形式后期会有优化,具体优化会再贴一个模块)
6.数据库查询配置文件准备以及查询实现
git下载地址:点我下载
在文章之前先写几点本人搭建SpringWeb查询资料的感受,感觉很多文章都是只是在某一个点上进行讲解,没有一篇文章将所有这些东西完整的串起来的教程。另外,很多查询到的资料都是有其特地解决场景的(就如管中窥豹般只看到了目前的场景),所以文章发出后,大部分都会说文章没有用。长此以往的恶性循环就导致查到的资料只能解决特定场景,而且没有一个系统完整的解决方案就导致查询到的大部分资料都是无用资料,浪费查询时间不说,事情最终也没有解决。
1.使用Idea搭建SpringWeb项目初始环境
1.1新建项目
1.2创建Spring Initializr工程
1.3新建项目名称和工程名称
1.4SpringWeb项目选择引入Web中的Spring Web Start模块
注意:目前来看,Idea工具应该对Web中的名称展示属于Spring的模块都有加Spring前缀,如果以前的同学看到Spring Web Start以前命名为是Web模块不要奇怪,其实就是同样一个
1.5SpringWeb项目选择引入解析Html的模板引擎
1.6 选择放置工程的文件夹位置
1.7SpringWeb项目工程目录路径
1.8删除无用文件
1.9SpringWeb项目工程pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
1.9总结
到此,第一个知识点[使用Idea搭建SpringWeb项目初始环境]已经完成
该模块提交记录
2.加入访问Html页面和静态资源
2.1增加pom依赖
<!-- .html Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
2.2新建hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../static/hello/libs/hello.js"></script>
</head>
<body>
您好
</body>
</html>
2.3新建hello.js
2.4配置访问端口号和静态资源访问配置
server:
address: 0.0.0.0
port: 10001
sessionTimeout: 3600
# 静态资源配置 默认值为 /**
spring.mvc.static-path-pattern: /static/**
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations: classpath:/static/
# 开发环境中关闭缓存便于测试
spring.thymeleaf.cache: false
spring.thymeleaf.mode : LEGACYHTML5
2.5新建访问hello.html控制器
package com.mon.project.model.welcomleDemo.contorller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/welcome")
public class WelcomeController {
/**
* hello.html页面
* @return
*/
@RequestMapping("welcomeIndex")
public String welcomeIndex(Model model){
return "hello";
}
}
2.6启动ProjectApplication访问页面
http://localhost:10001/welcome/welcomeIndex
2.7总结
至此,第二个知识点[加入访问Html页面和静态资源]已完结,最后该知识点完成后目录层级如下
该模块提交记录
因为一篇文章写完会太长,所以分为四篇文章进行拆分,其他知识点请看
1.使用Idea搭建SpringWeb项目初始环境
2.加入访问Html页面和静态资源
3.返回动态的Html页面处理
4.断言异常拦截处理以及自定义增加请求参数
5.引入logback日志记录(日志记录形式后期会有优化,具体优化会再贴一个模块)
6.数据库查询配置文件准备以及查询实现