SpringBoot Web项目 解析
1、Web项目
1.1 导入相关前端文件
1.2 设置首页路径
SpringBoot默认会在首页index.html都放在静态资源的三个文件夹下获取首页(By default, Spring Boot serves static content from a directory called /static
(or /public
or /resources
or /META-INF/resources
) in the classpath or from the root of the ServletContext
) https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#boot-features-spring-mvc-static-content,但是静态文件夹下的html,模板引擎Thymeleaf又没法读取,模板引擎Thymeleaf又要求放置在 src/main/resources/templates
.,才能读取
为了使用模板引擎的强大功能,需要将static里面的index.html(随便乱写一个)映射到 模板引擎能读取的目录里面某个真首页log.html。
说明:把项目相关的所有html都放到src/main/resources/templates目录下,其他的css,js可以依然放到原静态文件夹下
关于自动配置,前面已经说了,SpringBoot都有默认配置,但如果你对SpringBoot的配置不满意,可以自己写配置。SpringBoot会自动识别,并启用,显然这里需要重新配置路径。
配置方法:https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration
class of type WebMvcConfigurer
but without @EnableWebMvc
.
注意:网上的老教程还是WebMvcConfigurerAdapter
项目中找一个目录 /java/com/Tjjj/项目名/config
在这个目录下,写自己的配置类。
@Configuration
public class MyMvcConfig extends WebMvcConfigurer{@Bean//将组件注册到容器public WebMvcConfigurer webMvcConfigurer(){ //重新获取一个自定义的WebMvcConfigurer对象作为配置对象,并添加到容器中WebMvcConfigurer adapter = new WebMvcConfigurerAdaper(){@Overridepublic void addViewControllers(ViewControllerRegistry registry){registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("main.html").setViewName("dashboard");}};return adapter;}
}
说明:应该可以直接重写 addViewControllers方法,我觉得造个对象来重写,麻烦了,但是某个视频教程这么写。先这样吧
@Configuration
public class MyMvcConfig extends WebMvcConfigurer{public void addViewControllers(ViewControllerRegistry registry){registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");}
}
1.3 重写src/main/resources/templates目录下,login.html 的引用(在这个目录下,已经解锁好模板引擎功能了,重写引用的外部资源)
(1)公共资源,比如jquery,bootstrap等等,全部改用webjars
交给maven自动下载,使用方法,参考https://blog.csdn.net/chengqingshihuishui/article/details/111406057 2.1
下载好以后,一般放在maven.org.webjars:xxxxx3.0.0
去类路径下找到资源(以下载的bootstrap.jar为例)bootstrap-4.0.0.jar(classpath)/META-INF/resources/webjars/bootstrap/4.0.0/css/bootstrap.css
将原来静态资源的地址,通过 th:xx 替换成新地址
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
(2)其他自有,图片,js,css等自有资源
还是用模板引擎重写一次,重写的好处就是。以后哪一天,项目访问名变了,可以通过SpringBoot的配置,瞬间把外部引用路径一次修改完。
<!--自有css资源,直接复制原静态路径-->
<link herf="asserts/css/signin.css" th:herf="@{/asserts/css/signin.css}" rel="stylesheet">
<!--自有图片资源,还是直接复制原静态路径-->
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:src="@{/asserts/img/bootstrap-solid.svg}">
2、登录界面的国际化(看到有中文的地方,就对应一个英文)
效果图:
(1)编写国际化配置文件 https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#boot-features-internationalization
step1:在项目resources文件夹下,创建一个文件夹用于存放国际化文件,命名i18n
由于是login.html页面的国际化文件,因此将配置文件取名为login.properties
SpringBoot会自动识别这是国际化配置文件,就会自动进入国际化视图
step2:在有一个默认配置文件的基础上,再加入 中文配置文件,或者英文配置文件
取名为login_en_US.messages.properties 和 login_zh_CN.properties
IDEA进入国际化视图以后,可以一个属性,同时配置3个文件的值
//最终效果 以默认文件login.properties为例
login.btn=登录~
login.password=密码~
login.remember=记住我~
login.tip=请登录~
login.username=用户名~
step3 SpringBoot自动配置好了管理国际化资源的组件,但是根据官方文档,默认国际化的配置文件是message.propertis(这教程,明明可以用默认的多爽,非要玩自定义目录),需要用主配置文件将资源改成login.properties 系列基础名。
说明:login就是基础名,login_XXXX ,就不是基础名
//进入主配置文件application.properties
spring.messsages.basename = i18n.login
//就将基础名从默认的message.改成了login
step4 去login.html页面(首页),获取国际化的值
根据教程,thymeleaf模板引擎中,#{...}专门用于获取国际化信息,详情见thymeleaf官方文档4.1
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#messages
<h1 class="ss" th:text="#{login.tip}">Please Sign in</h1>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" name="username" placeholder="Username" th:placeholder="#{login.username}">
<!--input是自结束标签,没得th:text,因此用行内表达式-->
<input type="checkbox" value="remember-me">[[#{login.remember}]]
step5 实现中、英文 按钮切换语言
国际化的原理是,根据浏览器表头的传来的 国家/地区(一个locale对象) ,然后被SpringBoot的spring.web.locale-resolver 解析器解析,从而告诉模板引擎该展示什么国家的语言。
<!--手动选择好对应的语言后,让表头自动带上相关地区语言-->
<a class="yy" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="yy" th:href="@{/index.html(l='en_US')}">English</a>
重新写locale对象(也是一个配置),把http表头的 可能被点击的超链接信息写进去
找个目录专门写不满意的配置类,比如java/com/tjj/.../component 位置
说明:SpringBoot接口里面大量用了默认方法,所以很多方法不重写,也不报错
public class MyLocaleResolver implements LocaleResolver{@Overridepublic Locale resolveLocale (HttpServletRequest request) //获取一个Locale对象String l = request.getParameter("l"); //获取http表头请求的l属性的值Locale locale = Locale.getDefault(); //如果表头里面的l没有值if(!StringUtils.isEmpty(l)){ //如果这个l有值,即点击了中文或者EnglishString[ ] splt = l.split("_"); //按照_把l的值分成两段,放到splt数组里面locale = new Locale(split[0],split[1]);//Locale(String language, String country)构造器}return locale;}
}
找到配置文件目录/java/com/Tjjj/项目名/config 继续写 MyMvcConfig类,继续向容器添加组件(添加上面的locale对象)
@Configuration
public class MyMvcConfig extends WebMvcConfigurer{@Bean//将组件注册到容器public LocaleResolver localeResolver(){return new MyLocaleResolver();}
}
3、登录,拦截器
3.1 登录
(1)用Thymeleaf将表单的action改了,提交的时候,http表头就会 有 /user/login 点击登录以后,input的name和value 会一起发送走
<form class="form-sin" action="dashboard.html" th:action="@{/user/login}" method="post"><!--input标签里面,name就是键,用户在文本框里输入的,就是值--><input type="text" name="username" placeholder="Username" th:placeholder="#{login.username}"><input type="password" name="password" placeholder="Password" th:placeholder="#{login.password}">
(2)编写Controller来处理浏览器发来的/user/login (模板引擎已经修改好)
在专门的controller文件夹下,src/java/.../controller 编写LoginController类
https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#boot-features-spring-mvc
The Spring Web MVC framework (often referred to as “Spring MVC”) is a rich “model view controller” web framework. Spring MVC lets you create special @Controller
or @RestController
beans to handle incoming HTTP requests. Methods in your controller are mapped to HTTP by using @RequestMapping
annotations.
(3)重定向网页,防止表单重复提交
@Controller/*它标记的类就是一个SpringMvc Controller对象,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。*/
public class LoginController{//@RequestMapping(value="/user/login",method=RequestMethod.POST)@PostMapping(Value="/user/login") //处理/user/loginpublic String login(@RequestParam("username") String username,@RequestParam("password") String password,Map<String,Object> map,//如果账号密码不对,返回一个信息,模板引擎会捕获mapHttpSession session){ if(StringUtils.isEmpty(username)&&"123456".equals(password)){//有用户名发送过来,并且密码是123456 则发送成功session.setAttribute("loginUser",username);return "redirect:/main.html"; //重定向,先去main.html,然后再由main映射dashboard网页}else{//登录失败map.put("msg","用户密码错误");return "login";//返回登录页面,并且提示密码错误信息}}
}
如果账号密码不对,前端模板引擎捕获通过捕获map的key 即msg,显示值 用户密码错误,并加点样式
<!--判断后台的msg到底有没有值,如果有值就显示出来-->
<p style="color:red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
做重定向配置
@Configuration
public class MyMvcConfig extends WebMvcConfigurer{@Bean//将组件注册到容器public WebMvcConfigurer webMvcConfigurer(){ //重新获取一个自定义的WebMvcConfigurer对象作为配置对象,并添加到容器中WebMvcConfigurer adapter = new WebMvcConfigurerAdaper(){@Overridepublic void addViewControllers(ViewControllerRegistry registry){registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("main.html").setViewName("dashboard"); //实现重定向}};return adapter;}
}
此时,直接访问localhost:8080/main.html 也可以直接进主页了,登录页面,就失去意义了。因此需要拦截器
3.2 拦截器 都是现成的接口(implements HandlerInterceptor),只管重写方法就是了
step1:在java/com/.../component 文件夹 写拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object user = request.getSession().getAttribute("loginUser");if(user==null){//未登录,返回登录页面request.setAttribute("msg","没有权限请先登录");request.getRequestDispatcher("/index.html").forward(request,response);return false;}else{//已登录,放行请求return false;}}
}
step2:注册拦截器
@Configuration
public class MyMvcConfig extends WebMvcConfigurer{@Bean//将组件注册到容器public WebMvcConfigurer webMvcConfigurer(){ //重新获取一个自定义的WebMvcConfigurer对象作为配置对象,并添加到容器中WebMvcConfigurer adapter = new WebMvcConfigurerAdaper(){@Overridepublic void addViewControllers(ViewControllerRegistry registry){registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("main.html").setViewName("dashboard"); //实现重定向}};//注册进来的拦截器拦截一切路径(/**),除了首页和登录页以及相关转换@Overridepublic void addInterceptors(){registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login");}return adapter;}
}
扩展:开发期间,模板引擎修改页面以后,实时生效的方法
禁用模板引擎缓存
#禁用缓存 https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#howto-reload-thymeleaf-template-content
spring.thymeleaf.cache=false
页面修改完成后,ctrl+F9重新编译
如果账号密码不对,返回一个msg
扩展:th:if用法,官方文档 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#conditional-evaluation
内置对象#strings的用法 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#strings
SpringBoot Web项目 解析相关推荐
- 视频教程-SpringBoot Web项目案例视频课程-Java
SpringBoot Web项目案例视频课程 拥有10余年项目实战经验. 2006-2011在nttdata从事对日软件开发类工作. 2011-2015在HP从事技术服务工作. 擅长于j2ee相关的软 ...
- springMVC web项目转springboot web项目的杂谈
文章背景: 一个老的web项目是用springMVC做的,最近需要修改一些功能,然后用本地部署的Tomcat启动,启动过程中各种报错,在网上百度半天都是spring版本的问题,纠结了一段时间,终于有了 ...
- Springboot web项目简单统计在线人数
web项目中都是短连接,无法根据连接的开启与断开做判断,只能简单的根据session的创建与销毁来判断在线人数,做不到实时统计. 好了,直接上代码 #1.springboot的启动类加上@Servle ...
- 教你如何在window服务器上快速部署SpringBoot web项目
小白笔录,大神请绕路.欲在服务器上部署项目,必先细细考量服务器上是否已经搭建好环境.此处以 web项目部署在 tomcat 上为例,前三个步骤以实际情况,读者自行跳过. 一.搭建 jdk 环境 在搭建 ...
- idea springboot web项目创建并集成mybatis+springmvc(二)
完整项目下载地址:https://download.csdn.net/download/qq_34288630/10519597 springboot项目创建步骤:https://blog.csdn. ...
- SpringBoot Web项目结构梳理
摘要 讲道理,每个项目都有自己的结构,大家都各不相同,这里讲一个我比较喜欢Web项目模块结构风格,感觉还不错,整体项目结构清晰. 一.项目结构说明 项目整体结构如下: ftp_server ftp_s ...
- SpringBoot Web项目Mock测试
1.环境准备 Spring-boot官方给我们提供了测试用的场景启动器:spring-boot-starter-test 如果我们用IDEA创建一个spring项目,默认会给我们在pom里面引入这个依 ...
- springboot web项目_Vue、Spring Boot开发小而完整的Web前后端分离项目实战12
第12讲 tabs选项卡制作讲解 1.1.tabs选项卡组件: 1. tabs 组件 2.常用属性: value :选中选项卡的name type :选项卡风格 可选择 card / border-c ...
- java war包怎么运行_springboot web项目打jar或者war包并运行的实现
(一)springboot web项目打jar包 1.打包 两种打包方式 maven命令打包 切换目录到工程根下,pom.xml所在位置,运行maven的打包命令 mvn clean package ...
- 【SpringBoot零基础案例01】【IEDA 2021.1】如何创建一个SpringBoot框架web项目
一.创建一个空项目 点击[File]- [New]- [Project-],新建一个空项目 选择[Empty Project]点击[Next] 填写项目名称,选择项目本地存储路径,点击[Finish] ...
最新文章
- C语言函数大全(a开头)
- python中abc属于字符串吗_Python基础学习:字符串
- STM32应用实例六:与MS5837压力传感器的I2C通讯
- mysql 服务无法启动 没有报告任何错误_My SQL学习之路(一)
- 使用绘图类库flotr2来绘制HTML5的图形和图表
- android权限 启动失败,Android 6.0打开失败:EACCES(权限被拒绝)
- print函数python_带有结束参数的Python print()函数
- 如何写一篇合格的论文(清华大学刘知远)
- goland配置mysql失败_GoLand配置数据库、远程host以及远程调试
- AEF横空出世——查询语法详解
- MergeSort(合并排序)
- 塞班S60v3版平台手机证书权限内容大解析
- 程序员日常工作英文记录
- 湖南工业大学计算机学院有哪些社团,湖南工业大学学生社团联合会
- (啤酒,红酒,白酒,料酒)豆瓣(剁椒)鲫鱼做法记录
- PL0编译器分析与语法扩展
- Java小程序木叶村_恋爱球滚动的天空
- 智能化引领中国铁路发展
- linux QQ无法显示图片和自定义头像
- trt 使用trtexec工具ONNX转engine