SpringBoot简化spring的框架
SpringBoot自动TomCat容器
SpringBoot界面使用HTML 也可以使用JSP 但是不推荐使用JSP
SpringBoot项目下的Resources下的文件夹 static存放静态资源 templates存放界面
image

创建SpringBoot项目

image

添加依赖

image

测试项目

控制器

package com.it.helloboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
*RestController=Controller+ResponseBody
*
**/
@RestController
public class Testcontroller {

@RequestMapping("/test")
public String test(){
return "SpringBoot Test";
}
}

访问

localhost:端口/访问的路径
http://localhost:8090/test

SpringBoot配置

SpringBoot配置 分为2种 一种是yml 一种properties 2种配置都可以使用 挑一种使用即可

若2种都使用的话 优先选择properties

application.properties

#配置端口
server.port=8090

application.yml

yml参考

写对了会高亮

YML是什么

YAML (YAML Ain’t a Markup Language)YAML不是一种标记语言,通常以.yml为后缀的文件,是一种直观的能够被电脑识别的数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,一种专门用来写配置文件的语言。可用于如: Java,C/C++, Ruby, Python, Perl, C#, PHP等。

YML的优点

  1. YAML易于人们阅读。
  2. YAML数据在编程语言之间是可移植的。
  3. YAML匹配敏捷语言的本机数据结构。
  4. YAML具有一致的模型来支持通用工具。
  5. YAML支持单程处理。
  6. YAML具有表现力和可扩展性。
  7. YAML易于实现和使用。

约束

  1. k: v 表示键值对关系,冒号后面必须有一个空格
  2. 使用空格的缩进表示层级关系,空格数目不重要,只要是左对齐的一列数据,都是同一个层级的
  3. 大小写敏感
  4. 缩进时不允许使用Tab键,只允许使用空格。
  5. 松散表示,java中对于驼峰命名法,可用原名或使用-代替驼峰,如java中的lastName属性,在yml中使用lastName或 last-name都可正确映射。
#配置端口
server:
port: 8090

热部署

static里面的文件是可以直接显示的 location:8090/main.html (main.html在static下面)

模板文件夹里面的需要通过返回进入界面

依赖

<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

application.properties

#配置热部署
spring.devtools.restart.enabled=true
#需要热部署的文件路径
spring.devtools.restart.additional-paths=src/main/java

配置IDEA2021
Settings

image

image

thymeleaf标签

依赖

<!--模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

application.properties


#模板引擎
spring.thymeleaf.enabled=true
#设置编码
spring.thymeleaf.encoding=UTF-8
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#后缀
spring.thymeleaf.suffix=.html
#严格的语法检查
spring.thymeleaf.mode=HTML
#是否使用缓存 开发器不要打开
spring.thymeleaf.cache=false

界面引入

xmlns:th="http://www.thymeleaf.org"

image

跳转到指定的界面

//get请求
@GetMapping("/user")
//跳到templates文件夹下的users文件夹下的index
@GetMapping("/user")
public String user(ModelMap map){
System.out.println("运行2!");
System.out.println("测试2");
return "users/index";
}

点击事件

image

th:text显示文本

<!--th:text 显示文本 后台的文本显示到标签中-->
<p th:text="${test}">基本数据</p>
<!--th:utext 使用标签 识别标签-->
<p th:utext="${test}"></p>

控制器

@GetMapping("/admin")
public String admin(ModelMap map){
map.put("test","<h1>hrlllo</h1>");
return "admins/index";
}

th:utext显示文本(可识别标签)

th:utext和th:text的区别就是 th:utext可以识别标签 th:text不可以识别标签

<!--th:utext 使用标签 识别标签-->
<p th:utext="${test}"></p>

控制器

@GetMapping("/admin")
public String admin(ModelMap map){
map.put("test","<h1>hrlllo</h1>");
return "admins/index";
}

显示实体

<!--实体类 直接xxx.实体属性名-->
<h1>取实体</h1>
<p th:text="${user.id}"></p>
<p th:text="${user.name}"></p>
<p th:text="${user.pass}"></p>

控制器

@GetMapping("/admin")
public String admin(ModelMap map){
List lis=new ArrayList();
Users us=new Users(1,"张三","123456",new Date());
Users us2=new Users(2,"张三2","123456",new Date());
Users us3=new Users(3,"张三3","123456",new Date());
lis.add(us);
lis.add(us2);
lis.add(us3);
map.put("eat",lis);
return "admins/index";
}

日期格式化

<h1>日期格式化</h1>
<!--日期格式化 #dates.format(要格式化的属性,'格式化的模板')-->
<p th:text="${#dates.format(user.birthday,'yyyy-MM-dd hh:mm:ss')}"></p>

多属性取值

一个实体很多属性时 可以省写前面的名字

<h1>*取值</h1>
<div th:object="${user}">
<p th:text="*{id}"></p>
<p th:text="*{name}"></p>
<p th:text="*{pass}"></p>
</div>

thif IF判断标签

<h1>if判断</h1>
<!--@相当于base相对路径 th:src="@{/路径}" th:if是if判断 -->
<img th:if="${usif!=null}" th:src="@{/pic/149.jpg}" width="600px" height="600px">

@获取项目路径

th:src获取图片路径

@{/图片路径}

<img th:if="${usif!=null}" th:src="@{/pic/149.jpg}" width="600px" height="600px">

th:href引入文件

@{/文件路径}

<!--href指定路径 th:href="@{/样式的路径}"-->
<link rel="stylesheet" th:href="@{/css/style.css}"/>

switch标签

<h1>switch标签</h1>
<!--Switch标签 th:switch="${属性}" th:case="值" th:case="*"其他 -->
<div th:switch="${role}">
<p th:case="admin">管理员</p>
<p th:case="teach">老师</p>
<p th:case="student">学生</p>
<p th:case="*">祖安人</p>
</div>

控制器

@GetMapping("/admin")
public String admin(ModelMap map){
map.put("role","teach");
return "admins/index";
}

th:each循环

<h1>循环</h1>
<table border="1px" cellspacing="0px" style="text-align: center">
<tr>
<td>ID</td>
<td>姓名</td>
<td>密码</td>
<td>出生年月</td>
</tr>
<tr th:each="user :${eat}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.pass}"></td>
<td th:text="${user.birthday}"></td>
</tr>
</table>

控制器

@GetMapping("/admin")
public String admin(ModelMap map){
List lis=new ArrayList();
Users us=new Users(1,"张三","123456",new Date());
Users us2=new Users(2,"张三2","123456",new Date());
Users us3=new Users(3,"张三3","123456",new Date());
lis.add(us);
lis.add(us2);
lis.add(us3);
map.put("eat",lis);
return "admins/index";
}

th:each得到当前循环的数

默认就是冒号前面的变量+Stat.count

下标就是 index

image

th:href放数据库的数据

th:href="@{${webconfig.websitegitee}}"

th:attr自定义标签属性

自定义属性为data-content="数据库数据"
th:attr="data-content=${webconfig.websiteqq}"

th:block隐藏显示标签

th:block 可以配合th:if使用 可以实现上一页下一页的显示
<th:block th:if="${wzconfig.pageNum>1}">
<a href="#" class="ui mini teal basic button">上一页</a>
</th:block>

字保留部分字符串 其他用点代替

{#strings.abbreviate(str,10)}//  str截取0-10位,后面的全部用…这个点代替,注意,最小是3

循环map

controller
Map<String, List<Article>> blmap=arse.findyearblog();
System.out.println(blmap);
mp.put("blmap",blmap);

前台
<th:block th:each="articlb:${blmap}">
//key
<h2 class="ui center aligned header" th:text="${articlb.key}">2018</h2>
<div class="ui fluid vertical menu">
//循环value 因为value是list 所有each
<a href="#" target="_blank" th:each="blog:${articlb.value}" class="item">
<span>
<i class="mini teal circle icon"></i><span th:text="${blog.articletitle}">关于刻意练习的清单</span>
<div class="ui teal basic left pointing label m-padded-mini " th:text="${#dates.format(blog.createtime, 'MM月dd')}">9月03</div>
</span>
<div class="ui orange basic left pointing label m-padded-mini ">原创</div>
</a>

</div>
</th:block>

th:action from表单提交

//搜索 回车也可以 点击也可以
<form name="search" action="#" target="_blank" th:action="@{/search}">
<div class="ui icon inverted transparent input">
<input type="text" name="query" placeholder="search....">
<i class="iconfont icon-sousuo" onclick="document.forms['search'].submit();"></i>
</div>
</form>

controller

/**
* 搜索
* @param query
* @return
*/
@GetMapping("/search")
public String search(ModelMap mp,String query){
System.out.println(query);
return "fontdesk/search";
}

th:utxt可以识别html

//博客内容时可以使用
th:utext="${detail.content}"

th:unless除非

可以配合重定向带参数使用

<div class="ui success message" th:unless="${#strings.isEmpty(message)}">
<i class="close icon"></i>
<div class="header">提示:</div>
<p th:text="${message}">恭喜,操作成功!</p>
</div>

redirect重定向带参数

@GetMapping("/delblog/{bid}")
public String delblog(@PathVariable("bid") int bid,RedirectAttributes attributes){
int desu=base.delblog(bid);
if(desu>0){
attributes.addFlashAttribute("message", "删除成功!");
}else{
attributes.addFlashAttribute("message", "删除失败!");
}
return "redirect:/adblog";
}

界面取值

<div class="header">提示:<p th:text="${message}">恭喜,操作成功!</p></div>

Mybatis整合

依赖

<!--Mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>

<!--数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<!--阿里连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>

项目截图

image

application.properties

#数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/heros?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root

#mybatis配置
#配置文件
mybatis.mapper-locations=classpath:mapper/*.xml
#开启别名的实体
mybatis.type-aliases-package=com.it.helloboot.entity
#开启驼峰命名法
mybatis.configuration.map-underscore-to-camel-case=true
#使用列别名 替换列名
#mybatis.configuration.use-column-label=true

HerosMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.it.helloboot.dao.HerosDao">
<select id="seall" resultType="Heros">
select * from heros
</select>
</mapper>

dao层

package com.it.helloboot.dao;

import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface HerosDao {
/**
* 查询所有
* @return
*/
public List seall();
}

实体

package com.it.helloboot.entity;

import lombok.Data;

@Data
public class Heros {
public int id;
public String name;
public String nickname;
public int sex;
public String first;
}

service

package com.it.helloboot.service;

import java.util.List;

/**
* @author 羡羡
*/
public interface HerosService {
public List getHeros();
}

serviceimpl

package com.it.helloboot.service.impl;

import com.it.helloboot.dao.HerosDao;
import com.it.helloboot.service.HerosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 羡羡
*/
@Service
public class HerosServiceImpl implements HerosService {

@Autowired
HerosDao he;

@Override
public List getHeros() {
System.out.println("进入HerosService!");
return he.seall();
}
}

测试dao

package com.it.helloboot;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.helloboot.dao.HerosDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.List;

@SpringBootTest
public class HerosTest {

@Autowired
HerosDao he;

@Test
public void seall(){
List lis=he.seall();
System.out.println(lis);
}
}

控制器

package com.it.helloboot.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.helloboot.service.HerosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Arrays;
import java.util.List;

/**
* @author 羡羡
*/
@Controller
public class HerosController {
@Autowired
HerosService hers;

@RequestMapping("/showheros")
public String sh(ModelMap map){
List lis=hers.getHeros();
map.put("heros",lis);
return "users/heros";
}
}

界面显示

<table border="1px" cellspacing="0px" style="text-align: center;width: 700px;margin-left: 416px">
<tr>
<td>ID</td>
<td>名称</td>
<td>昵称</td>
<td>性别</td>
<td>职业</td>
</tr>
<tr th:each="h : ${heros}">
<td th:text="${h.id}"></td>
<td th:text="${h.name}"></td>
<td th:text="${h.nickname}"></td>
<td th:text="${h.sex==1 ? '女' : '男'}"></td>
<td th:text="${h.first}"></td>
</tr>
</table>

mybatis分页

需要配合mybatis整合使用

依赖

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

项目截图

image

HerosMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.it.helloboot.dao.HerosDao">
<select id="seall" resultType="Heros">
select * from heros
</select>
</mapper>

实体

package com.it.helloboot.entity;

import lombok.Data;

@Data
public class Heros {
public int id;
public String name;
public String nickname;
public int sex;
public String first;
}

dao层

package com.it.helloboot.dao;

import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface HerosDao {
/**
* 查询所有
* @return
*/
public List seall();
}

service

package com.it.helloboot.service;

import java.util.List;

/**
* @author 羡羡
*/
public interface HerosService {
public List getHeros();
}

serviceimpl

package com.it.helloboot.service.impl;

import com.it.helloboot.dao.HerosDao;
import com.it.helloboot.service.HerosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 羡羡
*/
@Service
public class HerosServiceImpl implements HerosService {

@Autowired
HerosDao he;

@Override
public List getHeros() {
System.out.println("进入HerosService!");
return he.seall();
}
}

控制器

package com.it.helloboot.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.helloboot.service.HerosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Arrays;
import java.util.List;

/**
* @author 羡羡
*/
@Controller
public class HerosController {
@Autowired
HerosService hers;

@RequestMapping("/showheros")
public String sh(ModelMap map){
PageHelper.startPage(1,10);
List lis=hers.getHeros();
PageInfo pa=new PageInfo(lis,10);
map.put("heros",pa);
return "users/heros";
}

@RequestMapping(path = "/showheros/{curr}",method = RequestMethod.GET)
public String show(ModelMap map, @PathVariable("curr") int curr){
if(curr==0){
curr=1;
}
PageHelper.startPage(curr,10);
List lis=hers.getHeros();
PageInfo pa=new PageInfo(lis,10);
map.put("heros",pa);
return "users/heros";
}
}

分页控制器简化

上面控制器简化

// 此方法 为上面控制器简化代码 
//前台拼接 th:href="${'/showheros?pagenum='+heros.prePage}"
@RequestMapping("/showheros")
public String sh(ModelMap map,@RequestParam(defaultValue = "1") int pagenum){
PageHelper.startPage(pagenum,10);
List lis=hers.getHeros();
PageInfo pa=new PageInfo(lis,10);
map.put("heros",pa);
return "users/heros";
}

普通路径参数其他示例

//示例1(路径不接其他东西)
pagenum是全名拼接的参数 设置默认值
@GetMapping({"/","/index"})
public String index(ModelMap mp, @RequestParam(defaultValue = "1") int pagenum) throws Exception {
PageInfo pa=new PageInfo(ls,10);
return "fontdesk/index";
}

image

路径参数多个分页示例

//路径参数多个时拼接注意不是& 是?
@GetMapping(path = "/blogtype/{blogid}")
public String blogtype(ModelMap mp,@PathVariable("blogid")int blogid,@RequestParam(defaultValue = "1") int pagenum){
//分页 每页8条
PageHelper.startPage(pagenum,8);
return "fontdesk/types";
}

image

测试

@Test
public void seall(){
PageHelper.startPage(1,10);
List lis=he.seall();
System.out.println(lis);
// ,后面是分页条的多少
PageInfo pa=new PageInfo(lis,10);
System.out.println(pa);
System.out.println("总页数:"+pa.getPages());
System.out.println("当前页:"+pa.getPageNum());
System.out.println("数据:"+pa.getList());
int [] panum=pa.getNavigatepageNums();
System.out.println("导航条:"+ Arrays.toString(panum));
}

界面

样式

* {
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
font-family: arial;
}
body {
text-align: center;
font-family: arial;
}

.pagination {
list-style: none;
display: inline-block;
padding: 0;
margin-top: 10px;
}

.pagination li {
display: inline;
text-align: center;
}

.pagination a {
float: left;
display: block;
font-size: 14px;
text-decoration: none;
padding: 5px 12px;
color: #fff;
margin-left: -1px;
border: 1px solid transparent;
line-height: 1.5;
}

.pagination a.active {
cursor: default;
}

.pagination a:active {
outline: none;
}

.modal-1 li:first-child a {
-moz-border-radius: 6px 0 0 6px;
-webkit-border-radius: 6px;
border-radius: 6px 0 0 6px;
}

.modal-1 li:last-child a {
-moz-border-radius: 0 6px 6px 0;
-webkit-border-radius: 0;
border-radius: 0 6px 6px 0;
}

.modal-1 a {
border-color: #ddd;
color: #4285F4;
background: #fff;
}

.modal-1 a:hover {
background: #eee;
}

.modal-1 a.active,
.modal-1 a:active {
border-color: #4285F4;
background: #4285F4;
color: #fff;
}

html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>显示英雄</title>
<link rel="stylesheet" th:href="@{/css/pagescss.css}"/>
</head>
<body>
<h1>Heros列表</h1>
<table border="1px" cellspacing="0px" style="text-align: center;width: 700px;margin-left: 416px">
<tr>
<td>ID</td>
<td>名称</td>
<td>昵称</td>
<td>性别</td>
<td>职业</td>
</tr>
<tr th:each="h : ${heros.list}">
<td th:text="${h.id}"></td>
<td th:text="${h.name}"></td>
<td th:text="${h.nickname}"></td>
<td th:text="${h.sex==1 ? '女' : '男'}"></td>
<td th:text="${h.first}"></td>
</tr>
</table>

<ul class="pagination modal-1">
<li th:if="${heros.PageNum>0}">
<li><a th:href="${'/showheros/1'}">首页</a></li>
<li><a class="prev" th:href="${'/showheros/'+heros.prePage}">&laquo</a></li>
</li>
<li th:each="g:${heros.navigatepageNums}">
<a th:class="${g==heros.pageNum ? 'active':''}" th:href="${'/showheros/'+g}" th:text="${g}">1</a>
</li>
<li th:if="${heros.nextPage>0}">
<li><a class="next" th:href="${'/showheros/'+heros.nextPage}">&raquo;</a></li>
<li><a th:href="${'/showheros/'+heros.pages}">尾页</a></li>
</li>

</ul>
</body>
</html>

image

跨域

package com.it.helloboot.config;

import com.it.helloboot.Interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* @author 羡羡
* 配置类
* 1、全网跨域
* 2、拦截器
*/
public class WebConfig implements WebMvcConfigurer{
/**
* 跨域
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
//所有
registry.addMapping("/**")
//支持的方法
/*allowedOrigins("*")*/
.allowedOriginPatterns("*")
//支持的方法
.allowedMethods("GET","PUT","DELETE","POST","HEAD","OPTIONS")
//证书
.allowCredentials(true)
//超时
.maxAge(3600)
//允许头
.allowedHeaders("*");
}
}

全局异常

ajax异常

package com.it.helloboot.config;

/**
* @author 羡羡
*
* 自定义ajax异常
*/
public class AjaxExecption extends Exception{

public AjaxExecption(String message) {
super(message);
}
}

JSON统一返回

JsonResult

package com.it.helloboot.entity;
/**
* @author 羡羡
*
* 统一返回JSON
*/
public class JsonResult {
int code;
String msg;
Object data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public JsonResult() {
}
public JsonResult(int code, String msg) {
this.code = code;
this.msg = msg;
}
public JsonResult(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
@Override
public String toString() {
return "JsonResult{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}

全局异常

普通异常不需要写什么 只要写了全局异常即可

package com.it.helloboot.config;

import com.it.helloboot.entity.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
* @author 羡羡
* 系统异常处理器
*/
@ControllerAdvice
public class SysExecptionHandler {

/**
* 普通自定义异常
* @param ex
* @return
*/
@ExceptionHandler(value = Exception.class)
public ModelAndView handleNormal(HttpServletRequest request, HttpServletResponse response, Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("errmsg",ex.getMessage());
mv.setViewName("error/err500");
return mv;
}

/**
* ajax异常
* @param ex
* @return
*/
@ExceptionHandler(value = AjaxExecption.class)
@ResponseBody
public JsonResult handleAjax(HttpServletRequest request, HttpServletResponse response,Exception ex){
JsonResult js=new JsonResult(500,ex.getMessage());
return js;
}
}

ajax异常测试

@RequestMapping("ajax")
@ResponseBody
public JsonResult js(int n) throws AjaxExecption {
JsonResult js;
try {
int f= 9/n;
js=new JsonResult(200,"成功!","查询成功!");
}catch (Exception e){
throw new AjaxExecption(e.getMessage());
}
return js;
}

404异常处理

建一个叫error的文件夹 然后里面有一个404界面即可

image

拦截器

拦截器类

package com.it.helloboot.Interceptor;



import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author 羡羡
*
* 登入拦截
*
* Component创对象
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("login标志!");
//判断拦截
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}

拦截器配置类

package com.it.helloboot.config;

import com.it.helloboot.Interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* @author 羡羡
* 配置类
* 1、全网跨域
* 2、拦截器
*/
@Configuration
public class WebConfig implements WebMvcConfigurer{

@Autowired
LoginInterceptor login;



@Override
public void addInterceptors(InterceptorRegistry registry) {
//增加拦截器
registry.addInterceptor(login)
//拦截的路径
.addPathPatterns("/**")
//排除的路径
.excludePathPatterns("/login");
//两个拦截器
/* registry.addInterceptor(login2)
//拦截的路径
.addPathPatterns("/**")
//排除的路径
.excludePathPatterns("/login");*/
}
}

打包成jar包

先点击clean 然后点击install 

java -jar 名字

访问路径 ip地址:端口/控制器名 http://47.101.177.78:8090/showheros/1

image

一直运行 关闭ssh窗口也ok

image

一直查看 日志文件

tail -f 文件  

关掉一直运行

image

多个html有共同的头或者尾部

参考
新建html文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer-fragment-head">
<nav class="ui inverted segment m-padded-tb-mini">
<div class="ui container">
<div class="ui inverted secondary stackable menu">
<h2 class="ui teal header item">Blog</h2>
<a href="index.html" class="active m-item item m-mobile-hide"><i class="iconfont icon-shouye"></i>首页</a>
<a href="types.html" class="m-item item m-mobile-hide"><i class="iconfont icon-fenlei"></i>分类</a>
<a href="tags.html" class="m-item item m-mobile-hide"><i class="iconfont icon-biaoqian"></i>标签</a>
<a href="archives.html" class="m-item item m-mobile-hide"><i class="iconfont icon-guidang"></i>归档</a>
<a href="about.html" class="m-item item m-mobile-hide"><i class="iconfont icon-guanyu"></i>关于我</a>
<div class="right m-item item m-mobile-hide">
<div class="ui icon inverted transparent input">
<input type="text" placeholder="search....">
<i class="iconfont icon-sousuo"></i>
</div>
</div>
</div>
</div>
<a href="#" class="ui menu toggle black icon button m-right-top m-mobile-show">
<i class="sidebar icon"></i>
</a>
</nav>
</footer>
</html>

关键

image

需要这一块的地方引用

th:replace=“路径文件夹名/html的文件名”::html文件里面的footter的th:fragment

image