SpringBoot:web开发

web开发demo:点击查看 LearnSpringBoot05Web

点击查看更多的SpringBoot教程

技术摘要

  1. webjars
  2. Bootstrap
  3. 模板引擎thymeleaf
  4. 嵌入式Servlet容器
  5. 注册web三大组件

一、webjars

webjars官网
简介

简介翻译
WebJars 是打包到 JAR(Java Archive)文件中的客户端 Web 库(例如 jQuery 和 Bootstrap)。 显式且轻松地管理基于 JVM 的 Web 应用程序中的客户端依赖项 使用基于 JVM 的构建工具(例如 Maven、Gradle、sbt...)下载客户端依赖项 了解您正在使用哪些客户端依赖项 传递依赖项会自动解析并通过 RequireJS 选择性加载 部署在 Maven 中心 公共 CDN。
pom.xml添加webjars依赖

pom.xml添加webjars依赖代码

bash 复制代码
    <!--
            https://www.webjars.org/

            WebJars介绍 https://blog.csdn.net/Adrian_Dai/article/details/80505076

            http://localhost:8084/webjars/jquery/3.6.4/jquery.js  访问webjars的jquery静态资源

            注意:http://localhost:8084/crud访问地址后面加/crud,
            因为在application.properties里配置了访问路径: server.servlet.context-path=/crud
            http://localhost:8084/crud/webjars/jquery/3.6.4/jquery.js  访问webjars的jquery静态资源
          -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.6.4</version>
        </dependency>

        <!--
        https://www.webjars.org/ 里找到 bootstrap

        bootstrap官网:https://getbootstrap.com/
        bootstrap中文网:https://www.bootcss.com/
        https://github.com/twbs/bootstrap

        http://localhost:8084/webjars/bootstrap/4.0.0/js/bootstrap.js  访问webjars的bootstrap静态资源

            注意:http://localhost:8084/crud访问地址后面加/crud,
            因为在application.properties里配置了访问路径: server.servlet.context-path=/crud
            http://localhost:8084/crud/webjars/bootstrap/4.0.0/js/bootstrap.js  访问webjars的bootstrap静态资源

        -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
<!--            <version>5.3.1</version>-->
            <version>4.0.0</version>
        </dependency>

项目启动后,访问webjars的jquery的jquery.js静态资源

项目启动后,访问webjars的bootstrap的js/bootstrap.js静态资源

二、Bootstrap

Bootstrap官网
Bootstrap中文网
Github里的Bootstrap

Bootstrap是美国Twitter公司的设计师Mark Otto和Jacob Thornton合作基于HTML、CSS、JavaScript 开发的简洁、直观、强悍的前端开发框架,使得 Web 开发更加快捷。Bootstrap提供了优雅的HTML和CSS规范,它即是由动态CSS语言Less写成。

三、模板引擎thymeleaf

thymeleaf官网
Github里thymeleaf
简介

简介翻译

Thymeleaf是一个现代的服务器端Java模板引擎,适用于web和独立环境。

Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板------HTML可以在浏览器中正确显示,也可以作为静态原型工作,允许开发团队之间更强的协作。

有了Spring框架的模块,与你最喜欢的工具的大量集成,以及插入你自己的功能的能力,Thymeleaf是现代HTML5 JVM web开发的理想选择------尽管它还有更多的功能。
添加spring-boot-starter-thymeleaf依赖
Spring-Boot的starters文档找到spring-boot-starter-thymeleaf

pom.xml添加spring-boot-starter-thymeleaf依赖代码

bash 复制代码
        <!--
            spring-boot-starter-thymeleaf
            https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using.build-systems.starters
            https://github.com/thymeleaf/thymeleaf

            TemplateEngineConfigurations
            org.springframework.boot.autoconfigure.thymeleaf


            把html页面放在 classpath:/templates/ ,thymeleaf就可以自动渲染了
         -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

把html页面放在 classpath:/templates/ ,thymeleaf就可以自动渲染了

四、嵌入式Servlet容器

MyServeltConfig.java类里配置嵌入式的servlet容器
查看支持嵌入其他servlet

MyServeltConfig.java代码

bash 复制代码
package com.example.learnspringboot05web.config;

import com.example.learnspringboot05web.filter.MyFilter;
import com.example.learnspringboot05web.listener.Mylistener;
import com.example.learnspringboot05web.servlet.Myservlet;
import org.springframework.boot.web.embedded.jetty.ConfigurableJettyWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.management.MemoryUsage;
import java.lang.reflect.Array;
import java.util.Arrays;

@Configuration
public class MyServeltConfig {

    //注册三大组件
    @Bean
    public ServletRegistrationBean myServlet() {
        //http://localhost:8084/crud/myServlet
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new Myservlet(), "/myServlet");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new MyFilter());
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
        return filterRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean mylistener(){
        ServletListenerRegistrationBean<Mylistener> registrationBean = new ServletListenerRegistrationBean<Mylistener>(new Mylistener());
        return registrationBean;
    }


    //配置嵌入式的servlet容器

    /*

        https://www.jianshu.com/p/b973476ccfd6   https://blog.csdn.net/qq_43843951/article/details/108049897
        Spring Boot2.0以上版本EmbeddedServletContainerCustomizer被WebServerFactoryCustomizer替代

     */
    @Bean
    public WebServerFactoryCustomizer<ConfigurableJettyWebServerFactory> webServerFactoryWebServerFactoryCustomizer() {
        return new WebServerFactoryCustomizer<ConfigurableJettyWebServerFactory>() {
            //定制嵌入式的servlet容器相关规则

            @Override
            public void customize(ConfigurableJettyWebServerFactory factory) {
                factory.setPort(8082);
            }
        };
    }
}

五、注册web三大组件

web三大组件分别是:

  1. Servlet

  2. Filter: 过滤器

  3. Listener :监听器
    对应的Bean类

  4. ServletRegistrationBean

  5. FilterRegistrationBean

  6. ServletListenerRegistrationBean
    在MyServeltConfig.java类里注册三大组件

Myservlet.java代码

bash 复制代码
package com.example.learnspringboot05web.servlet;

import com.sun.source.util.DocSourcePositions;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class Myservlet extends HttpServlet {
    //http://localhost:8084/crud/myServlet
    //处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello Myservlet");
    }
}

Mylistener.java代码

bash 复制代码
package com.example.learnspringboot05web.listener;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

public class Mylistener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Mylistener 执行了 contextInitialized web应用启动");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Mylistener 执行了 contextDestroyed web项目销毁");

    }
}

MyFilter.java代码

bash 复制代码
package com.example.learnspringboot05web.filter;

import jakarta.servlet.*;

import java.io.IOException;

public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("MyFilter 执行了 doFilter ");
        chain.doFilter(request, response );
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}

Mylistener组件监听结果

Servlet和MyFilter组件回调

项目启动后,在浏览器地址栏访问:http://localhost:8084/crud/myServlet

web获取到Servlet组件写入的数据
MyFilter组件回调

六、bootstrap和thymeleaf配合使用的效果

项目启动后,在浏览器地址栏里访问http://localhost:8084/crud/
账户:admin;密码:123456

登录成功进入主页

员工管理页面

编辑页面

添加员工页面

application.properties代码

bash 复制代码
#查看 ServerProperties 源码

server.port=8084
#spring.web.resources.static-locations=classpath:/hello, classpath:/test

# 禁止混存, 修改后 按住 commd + f9 重新编译
spring.thymeleaf.cache=false

# 访问路径必须是 crud ? http://localhost:8084/crud/
server.servlet.context-path=/crud
# 绑定国际化 从 i18n文件里读取
spring.messages.basename=i18n.login

#默认的格式:dd/MM/yyyy
spring.mvc.format.date=yyyy-MM-dd

#SpringBoot-RuntimeException缺少exception和message问题解决方法,  这个问题是由于SpringBoot2.0以上版本,需要在配置文件中指定server的异常对象和异常信息
# https://blog.csdn.net/qq_40898909/article/details/126346500     https://blog.csdn.net/qq_33879627/article/details/106621563
# 查看 ErrorProperties 源码 private IncludeAttribute includeMessage = IncludeAttribute.NEVER;  includeException 默认 false
server.error.include-exception=true
server.error.include-message=always

pom.xml代码

bash 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>LearnSpringBoot05Web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>LearnSpringBoot05Web</name>
    <description>LearnSpringBoot05Web</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--
        引入其他servlet

        jetty启动java.lang.ClassNotFoundException: jakarta.servlet.http.HttpSessionContext
        解决方法:pom文件中添加依赖

        jakarta.servlet
        jakarta.servlet-api
        5.0.0

        原因:此时的jetty是11.x版本的,不支持jakarta.servlet-api 6,改成5即可
        原文链接:https://blog.csdn.net/weixin_44866139/article/details/132006996
        -->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-web</artifactId>-->
<!--            <exclusions>-->
<!--                <exclusion>-->
<!--                    <groupId>org.springframework.boot</groupId>-->
<!--                    <artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--                </exclusion>-->
<!--            </exclusions>-->
<!--        </dependency>-->

<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-undertow</artifactId>-->
<!--&lt;!&ndash;            <artifactId>spring-boot-starter-jetty</artifactId>&ndash;&gt;-->
<!--                                    undertow  和 jetty 二选一                   -->
<!--        </dependency>-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--
            https://www.webjars.org/

            WebJars介绍 https://blog.csdn.net/Adrian_Dai/article/details/80505076

            http://localhost:8084/webjars/jquery/3.6.4/jquery.js  访问webjars的jquery静态资源

            注意:http://localhost:8084/crud访问地址后面加/crud,
            因为在application.properties里配置了访问路径: server.servlet.context-path=/crud
            http://localhost:8084/crud/webjars/jquery/3.6.4/jquery.js  访问webjars的jquery静态资源
          -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.6.4</version>
        </dependency>

        <!--
        https://www.webjars.org/ 里找到 bootstrap

        bootstrap官网:https://getbootstrap.com/
        bootstrap中文网:https://www.bootcss.com/
        https://github.com/twbs/bootstrap

        http://localhost:8084/webjars/bootstrap/4.0.0/js/bootstrap.js  访问webjars的bootstrap静态资源

            注意:http://localhost:8084/crud访问地址后面加/crud,
            因为在application.properties里配置了访问路径: server.servlet.context-path=/crud
            http://localhost:8084/crud/webjars/bootstrap/4.0.0/js/bootstrap.js  访问webjars的bootstrap静态资源

        -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
<!--            <version>5.3.1</version>-->
            <version>4.0.0</version>
        </dependency>

        <!--
            spring-boot-starter-thymeleaf
            https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using.build-systems.starters
            https://github.com/thymeleaf/thymeleaf

            TemplateEngineConfigurations
            org.springframework.boot.autoconfigure.thymeleaf


            把html页面放在 classpath:/templates/ ,thymeleaf就可以自动渲染了
         -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
相关推荐
南山十一少1 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
bin91532 小时前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
闲猫2 小时前
go orm GORM
开发语言·后端·golang
丁卯4043 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
晴空万里藏片云3 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一3 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
Tirzano3 小时前
springsecurity自定义认证
spring boot·spring
奶球不是球3 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7233 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
Σίσυφος19005 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库