springboot-web:
可以看到springboot文件中并没有webapp目录,所以我们需要解决以下问题:
导入静态资源
首页
jsp,模板引擎thylemeaf
装配扩展SpringMVC
增删改查
拦截器
国际化
静态资源过滤:
在这个地方能够看到可以加载的目录,在webjars官网上WebJars - Web Libraries in Jars,可以搜索到对应的maven坐标,将对应的依赖导入后即可以在浏览器中访问到
同样的在下面一个方法中,指向了下面几个目录,都可以被spring识别
这几个目录包括resources根目录都会被识别3+1
warjars 访问方式 localhost:8080/warjars/
resource>static(默认)>public localhost:8080/
首页:有两种方式,直接放在静态资源目录下,通过controller转发
在静态资源目录下建立index.html后,打开localhost:8080就可以直接访问到index页面
在controller中新建IndexController,定义如下方法,将index.html放在templates文件夹下也可以访问
@Controller
public class IndexController {
@RequestMapping("index")
public String index(){
return "index";
}
}
Spring Boot Reference Documentation 这个网页可以找到thymeleaf对应的pom依赖,使用thymeleaf必须要导入依赖
thymeleaf:首先导入依赖
html中所有的标签都可以被thymeleaf接管,需要加上 th: 元素名,就可以实现接管了
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <!--导入命名空间-->
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<div th:text="${msg}"></div> <!-- 使用 th: 元素名接管html的元素名 -->
</div>
</body>
</html>
但是需要注意,在首页位置好像并不能直接取到thymeleaf接管的元素,有点蒙蔽了,测试了点其他的没成功,等回头在学些jsp和html
语法(狂神的图)
controller
@RequestMapping("/t2")
public String test2(Map<String,Object> map){ //Model 传参也一样的
//存入数据
map.put("msg","<h1>Hello</h1>");
map.put("users", Arrays.asList("chendong","cd"));
//classpath:/templates/test.html
return "test";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>cd</title>
</head>
<body>
<h1>测试页面</h1>
<div th:text="${msg}"></div>
<!--不转义-->
<div th:utext="${msg}"></div>
<!--遍历数据-->
<!--th:each每次遍历都会生成当前这个标签:官网#9-->
<h4 th:each="user :${users}" th:text="${user}"></h4>
<h4>
<!--行内写法:官网#12-->
<span th:each="user:${users}">[[${user}]]</span>
</h4>
</body>
</html>
装配扩展SpringMVC:阅读源码,官方文档Spring Boot Reference Documentation
增加一个config目录,实现ViewResolver,并将其装配到springboot中(使用@bean)
额呵呵,没找到DispatchServlet这个类,没办法打断点,先附上代码,在DispatcherServlet类的doDispatch方法上打一个断点,运行时就会跑到断点处
public class MyViewResolver implements ViewResolver{
//我们写一个静态内部类,视图解析器就需要实现ViewResolver接口
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
@Bean //放到bean中
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
}
还是没找到,springmvc的等回过头在来写,先跳过了,有点复杂。