SpringBoot学习2:如何创建web项目

简介: SpringBoot学习2:如何创建web项目

问题

image.png

导入静态资源

image.png

我们通过查看这个类中的WebMvcAutoConfigurationAdapter类的addResourceHandlers方法。

在这里可以了解到

其加载静态资源的文件夹为以下几个

"classpath:/META-INF/resources/", "classpath:/resources/", 
"classpath:/static/", "classpath:/public/"

image.png

image.png

首页

还是在WebMvcAutoConfigurationAdapter类中我们可以找到

image.png

这说明其实就是再找静态资源目录下的index.html

动态网页 Thymeleaf 模板引擎

动态网页跳转

springBoot中文文档

https://felord.cn/_doc/_springboot/2.1.5.RELEASE/_book/pages/using-spring-boot.html#using-boot-starter

根据上方链接可以查询到springboot的依赖为

spring-boot-starter-thymeleaf

我们将其导入即可

我们修改coontroller为以下信息

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyTestController {
    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}

注意这里没有使用@ResponseBody注解,所以不是以json形式返回

所以我们查看Thymeleaf自动装配的源码ThymeleafProperties

image.png

由此可知我们只需要在templates里创建文件就可以达到webinfo相同的效果

我们在templates中创建test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>TTTTTTT</h1>
  <h1>est</h1>
</body>
</html>

此时访问http://localhost:8080/test

image.png

修改controller层的代码

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyTestController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("message","hello SpringBoot");
        return "test";
    }
}

使用model向前端传递了message参数

前端修改为

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1 >----<a th:text="${message}"></a></h1>
</body>
</html>

注意上面导入了 xmlns:th="http://www.thymeleaf.org"

此时访问http://localhost:8080/test

image.png

Thymeleaf 常用语法

${} 提取Attribute

controller

@Controller
public class MyTestController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("message","<h1>hello SpringBoot</h1>");
        List<String> lists = new ArrayList<String>();
        lists.add("aaa");
        lists.add("bbb");
        lists.add("ccc");
        model.addAttribute("lists",lists);
        return "test";
    }
}

test.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:text="${message}"></div>
    <div th:utext="${message}"></div>
    <hr>
    <h3 th:each="list:${lists}" th:text="${list}"></h3>
</body>
</html>

结果:

image.png

@{} 指定路径 (即使在转发后也可以找到对应路径)

<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">

th:fragment 创建模板(预制体)

创建预制体

  <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="tou">
    <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Company name</a>
    <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
    <ul class="navbar-nav px-3">
      <li class="nav-item text-nowrap">
        <a class="nav-link" th:href="@{/templates/index.html}">Sign out</a>
      </li>
    </ul>
  </nav>

th:insert="~{::}" 调用预制体且可以传参

<div th:insert="~{public/publlics::tou(active='main.html')}"></div>

if

th:class="${active=='main.html'? 'nav-link active': 'nav-link'}"

th:each="" 遍历 th:selected选中下拉列表

<select class="form-select" name="department.id" >
 <option th:each="dep:${deps}" th:selected="${dep.getId()==emp.getDepartment().getId()}" th:text="${dep.getId()+'---'+dep.getDepartmentName()}" th:value="${dep.getId()}"></option>
</select>

th:checked 选中单选框

<div class="form-check form-check-inline">
   <input th:checked="${emp.getSex()==1}" class="form-check-input" type="radio" name="sex" id="inlineRadio1" value="1">
   <label  class="form-check-label" for="inlineRadio1">男</label>
</div>
<div class="form-check form-check-inline">
   <input th:checked="${emp.getSex()==0}" class="form-check-input" type="radio" name="sex" id="inlineRadio2" value="0">
   <label  class="form-check-label" for="inlineRadio2">女</label>
</div>

#dates.format 日期格式化

th:value="${#dates.format(emp.getDate(),'yyyy-MM-dd')}"

MVC配置扩展

创建config类

package com.example.myfirstproject.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * @author 化粪池堵塞的凶手
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    //视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/hhhh").setViewName("test");
    }
}

注意要使用@Configuration注解,和实现WebMvcConfigurer接口

此时便可以通过访问http://localhost:8080/hhhh

来访问test了

类似这种设置还有很多

https://blog.csdn.net/zhangpower1993/article/details/89016503

https://blog.csdn.net/A434534658/article/details/112139041

注意不要使用@EnableWebMvc注解,因为此注解导入了DelegatingWebMvcConfiguration,而DelegatingWebMvcConfiguration又继承了WebMvcConfigurationSupport

image.png

而在WebMvcAutoConfiguration中可以看到导入WebMvcConfigurationSupport会使自动装配失效

image.png

国际化

前提条件:文件均设置为UTF-8

image.png

国际化主要需要以下几个步骤

1.在resource目录创建i18n文件夹并创建配置文件并添加内容

image.png

image.png

2.在application配置文件中配置i18n文件所在位置

image.png

3.创建区域解析类

/**
 * 国际化
 * @author 化粪池堵塞的凶手
 */
//@Repository
public class LocaleResolverConfig implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        Locale locale = Locale.getDefault();//若没有则采用默认
        String language = request.getParameter("l");
        System.out.println("===>"+language);
        if (!StringUtils.isEmpty(language)){
            String[] s = language.split("_");
            locale = new Locale(s[0],s[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }
}

4.将其通过配置类放入IOC容器中,注意Bean名需要是localeResolver。也可以直接在LocaleResolverConfig类上加上@Component("localeResolver")注解。

image.png

5.修改html

====5.1创建切换按钮

      <a th:href="@{index.html(l=zh_CN)}">中文</a>
      <a th:href="@{index.html(l=en_US)}">english</a>

====5.2将文字改为国际化形式

比如

<h1 class="h3 mb-3 font-weight-normal"  >请登录</h1>
 <input type="email" id="inputEmail" class="form-control" placeholder="账户" required autofocus>
 <button class="btn btn-lg btn-primary btn-block" type="submit" >login</button>

改为

<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.title}" ></h1>
 <input type="email" id="inputEmail" class="form-control" th:placeholder="#{login.address}" required autofocus>
 <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}"></button>

此时运行切换语言便可以看出效果

国际化补充

其实第三步和第四步可以省略,不过省略后会使用默认的解析器,下面中英文切换的超链接就失效了,网页只会随着浏览器设置的语言发生改变。

image.png

image.png

错误处理(404 500)

只需要在这里添加文件即可 500同理

image.png

   


相关文章
|
1天前
|
前端开发 IDE Java
"揭秘前端转Java的秘径:SpringBoot Web极速入门,掌握分层解耦艺术,让你的后端代码飞起来,你敢来挑战吗?"
【8月更文挑战第19天】面向前端开发者介绍Spring Boot后端开发,通过简化Spring应用搭建,快速实现Web应用。本文以创建“Hello World”应用为例,展示项目基本结构与运行方式。进而深入探讨三层架构(Controller、Service、DAO)下的分层解耦概念,通过员工信息管理示例,演示各层如何协作及依赖注入的使用,以此提升代码灵活性与可维护性。
|
4天前
|
开发框架 JSON .NET
ASP.NET Core 标识(Identity)框架系列(三):在 ASP.NET Core Web API 项目中使用标识(Identity)框架进行身份验证
ASP.NET Core 标识(Identity)框架系列(三):在 ASP.NET Core Web API 项目中使用标识(Identity)框架进行身份验证
|
5天前
|
Java 应用服务中间件 Apache
使用IDEA修改Web项目访问路径,以及解决Apache Tomcat控制台中文乱码问题
本文介绍了在IntelliJ IDEA中修改Web项目访问路径的步骤,包括修改项目、模块、Artifacts的配置,编辑Tomcat服务器设置,以及解决Apache Tomcat控制台中文乱码问题的方法。
10 0
使用IDEA修改Web项目访问路径,以及解决Apache Tomcat控制台中文乱码问题
|
4天前
|
开发框架 .NET API
如何在 ASP.NET Core Web Api 项目中应用 NLog 写日志?
如何在 ASP.NET Core Web Api 项目中应用 NLog 写日志?
|
4天前
|
开发框架 .NET API
.Net Core Console 项目如何使用 HttpClient 与 Web 服务通信
.Net Core Console 项目如何使用 HttpClient 与 Web 服务通信
|
5天前
|
应用服务中间件
2022年最新最详细在IDEA中配置Tomcat(含有详细图解过程)、建立使用IEDA建立一个Web项目的案例
这篇文章提供了在IntelliJ IDEA中配置Tomcat服务器的详细步骤,包括添加Tomcat Server、选择安装路径、添加项目Artifact,以及创建和展示Web项目的流程。
|
6天前
|
缓存 Java 应用服务中间件
2021年9月28日,老是遇到一些非常奇葩的问题。就离谱、好好的一个web项目就莫名奇妙坏了。
开发者在使用IDEA 2020编辑器搭建的SSM框架图书管理系统中,遇到删除功能异常问题,经过一系列尝试后发现是IDEA编译缓存导致的,最终通过重新编译项目解决了问题。
|
21天前
|
Java 测试技术 数据库
Spring Boot中的项目属性配置
本节课主要讲解了 Spring Boot 中如何在业务代码中读取相关配置,包括单一配置和多个配置项,在微服务中,这种情况非常常见,往往会有很多其他微服务需要调用,所以封装一个配置类来接收这些配置是个很好的处理方式。除此之外,例如数据库相关的连接参数等等,也可以放到一个配置类中,其他遇到类似的场景,都可以这么处理。最后介绍了开发环境和生产环境配置的快速切换方式,省去了项目部署时,诸多配置信息的修改。
|
1月前
|
Java 应用服务中间件 开发者
Java面试题:解释Spring Boot的优势及其自动配置原理
Java面试题:解释Spring Boot的优势及其自动配置原理
87 0