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

   


相关文章
|
2月前
|
搜索推荐 JavaScript Java
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。
|
3月前
|
安全 Java API
Java Web 在线商城项目最新技术实操指南帮助开发者高效完成商城项目开发
本项目基于Spring Boot 3.2与Vue 3构建现代化在线商城,涵盖技术选型、核心功能实现、安全控制与容器化部署,助开发者掌握最新Java Web全栈开发实践。
381 1
|
4月前
|
JavaScript Java 微服务
现代化 Java Web 在线商城项目技术方案与实战开发流程及核心功能实现详解
本项目基于Spring Boot 3与Vue 3构建现代化在线商城系统,采用微服务架构,整合Spring Cloud、Redis、MySQL等技术,涵盖用户认证、商品管理、购物车功能,并支持Docker容器化部署与Kubernetes编排。提供完整CI/CD流程,助力高效开发与扩展。
519 64
|
5月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
286 3
|
5月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
450 3
|
5月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
245 0
|
5月前
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
432 0
|
5月前
|
安全 JavaScript Java
java Web 项目完整案例实操指南包含从搭建到部署的详细步骤及热门长尾关键词解析的实操指南
本项目为一个完整的JavaWeb应用案例,采用Spring Boot 3、Vue 3、MySQL、Redis等最新技术栈,涵盖前后端分离架构设计、RESTful API开发、JWT安全认证、Docker容器化部署等内容,适合掌握企业级Web项目全流程开发与部署。
353 0
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
101 0
|
监控 Java Maven
springboot学习二:springboot 初创建 web 项目、修改banner、热部署插件、切换运行环境、springboot参数配置,打包项目并测试成功
这篇文章介绍了如何快速创建Spring Boot项目,包括项目的初始化、结构、打包部署、修改启动Banner、热部署、环境切换和参数配置等基础操作。
1187 0

热门文章

最新文章