SpringBoot - Web开发
SpringBoot Web开发
自动装配
SpringBoot到底帮我们配置了什么?我们能不能进行修改?能修改那些东西?能不能扩展?
- xxxAutoConfiguration...向容器中自动配置组件
- xxxProperties:自动配置类,装配配置文件中自定义的一些内容
web开发要解决的问题:
-
导入静态资源(html,css,js……)
-
首页
-
jsp(模版引擎Thymeleaf)
-
装配扩展SpringMVC
-
增删改查
-
拦截器
-
国际化
(5.6.7见后续)
静态资源
总结:
- 在springboot中,我们可以使用一下方式处理静态资源
- wabjars 映射路径为:
localhost:8080/webjars/
(下面的目录结构) - public,static,/**,resources 映射路径为:
localhost:8080/
(可以直接访问)
- wabjars 映射路径为:
- 优先级:resources > static(默认) > public
模板引擎
要使用thymeleaf,只需要导入对应的依赖就可以了,将html放在templates目录下即可
依赖:
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-java8time -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
-
导入约束
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <!--链接以@开头,文本用#取出--> <!--html的所有标签都可以被thymeleaf替换接管: th: + 标签名称 |接管后就可以使用表达式了-->
-
编写Controller类
@Controller public class IndexController { @RequestMapping("test") public String index(Model model){ model.addAttribute("msg","<h1>hello,springboot</h1>"); model.addAttribute("users", Arrays.asList("qinjiang","zhangsan","kuangshen")); return "test"; } }
-
在html取值
<!--html的所有标签都可以被thymeleaf替换接管: th: + 标签名称 |接管后就可以使用表达式了--> <div th:text="${msg}"></div> <div th:utext="${msg}"></div> <hr/> <h3 th:each="user:${users}" th:text="${user}"></h3> <!--<h3 th:each="user:${users}">[[${user}]]</h3>
类型 | 取值方式 |
---|---|
变量 | $ |
选择变量 | * |
消息 | # |
URL | @ |
片段表达式 | ~ |
扩展MVC
-
创建config文件夹下MyMVCConfig类
-
实现WebMvcConfigurer
// 扩展springmvc @Configuration public class MyMvcConfig implements WebMvcConfigurer { }
-
接管视图解析器
如果想自定义一些定制化的功能,只要写这个组件,让后将它交给springboot,springboot就会帮我们自动装配
// 扩展springmvc @Configuration public class MyMvcConfig implements WebMvcConfigurer { @Bean public ViewResolver myViewResolver(){ return new MyViewResolver(); } // 自定义了一个自己的视图解析器 MyViewResolver public static class MyViewResolver implements ViewResolver{ @Override public View resolveViewName(String viewName, Locale locale) throws Exception { return null; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)