SpringBoot学习笔记-4:第四章 Spring Boot Web 开发(2)

简介: SpringBoot学习笔记-4:第四章 Spring Boot Web 开发

扩展与全面接管 SpringMVC

1、扩展配置

package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CustomVmcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // super.addViewControllers(registry);
        // 浏览器的请求 /demo 到视图 /hello
        registry.addViewController("demo").setViewName("hello");
    }
}

2、全面接管

增加 @EnableWebMvc 后,自动配置失效

package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@EnableWebMvc
@Configuration
public class CustomVmcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // super.addViewControllers(registry);
        // 浏览器的请求 /demo 到视图 /hello
        registry.addViewController("demo").setViewName("hello");
    }
}

引入资源

模板资源: https://getbootstrap.net/

模板语法: https://www.thymeleaf.org/

webjars: https://www.webjars.org/

目录设置

resources/

   templates   模板文件

   static      静态文件

首页设置

package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CustomVmcConfig extends WebMvcConfigurerAdapter {
    // 设置首页位置,默认访问 public/index.html 没有经过模板引擎处理
    @Bean
    public WebMvcConfigurerAdapter CustomVmcConfig() {
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return adapter;
    }
}

国际化

默认根据浏览器语言获取对应国际化信息

1、配置语言文件

resources 资源文件夹下

├── i18n
│   ├── login.properties
│   ├── login_en_US.properties
│   └── login_zh_CN.properties

默认配置 login.properties

login.button=登录~
login.title=登录~
login.username=用户名~
login.password=密码~
login.remember=记住我~

英文配置 login_en_US.properties


login.button=Sign In

login.title=Login

login.username=UserName

login.password=Password

login.remember=Remenber Me


中文配置 login_zh_CN.properties


login.button=登录

login.title=登录

login.username=用户名

login.password=密码

login.remember=记住我


2、配置 application.yml


spring:

 messages:

   basename: i18n.login


3、模板文件中使用


<button th:text="#{login.button}"></button>

1

根据浏览器请求头设置语言


GET http://localhost:8080/

Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7



4、自定义国际化处理器

package com.example.demo.component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
 * 区域信息解析器
 * 自定义国际化参数,支持链接上携带区域信息
 */
public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getParameter("lang");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(lang)) {
            String[] list = lang.split("_");
            if (list.length == 2) {
                locale = new Locale(list[0], list[1]);
            }
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    }
}

启用自定义国际化处理器

package com.example.demo.config;
import com.example.demo.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * 配置首页视图
 */
@Configuration
public class CustomVmcConfig extends WebMvcConfigurerAdapter {
    @Bean
    public MyLocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }
}

优先获取查询参数返回语言设置

http://localhost:8080/?lang=zh_CN
http://localhost:8080/?lang=en_US
• 1
• 2

登陆&拦截器

开发期间模板引擎修改要实时生效


禁用模板引擎缓存

重新编译

<!--登录错误消息提示-->

<p

 style="color: red;"

 th:text="${msg}"

 th:if="${not #strings.isEmpty(msg)}"

></p>


拦截器进行登录检查


登录

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
public class LoginController {
    @PostMapping("/user/login")
    // 等价于 @RequestMapping(value = "/user/login", method = {RequestMethod.POST})
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String, Object> map,
                        HttpSession session
    ) {
        if (!StringUtils.isEmpty(username) && "123".equals(password)) {
            session.setAttribute("loginUser", username);
            // 登录成功 防止表单重新提交,做一个重定向
            return "redirect:/dashboard.html";
        } else {
            // 登录失败
            map.put("msg", "账号或密码不正确");
            return "login";
        }
    }
}

拦截器

package com.example.demo.component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 登录检查
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginUser = request.getSession().getAttribute("loginUser");
        // 未登录,返回登录页面
        if (loginUser == null) {
            request.setAttribute("msg", "没有权限,请先登录");
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        }
        // 已登录,放行
        else {
            return true;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

注册拦截器

package com.example.demo.config;
import com.example.demo.component.LoginHandlerInterceptor;
import com.example.demo.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * 配置首页视图
 */
@Configuration
@SuppressWarnings("all")
public class CustomVmcConfig extends WebMvcConfigurerAdapter {
    // 设置首页位置,默认访问 public/index.html 没有经过模板引擎处理
    @Bean
    public WebMvcConfigurerAdapter CustomVmcConfig() {
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            /**
             * 注册视图控制器
             * @param registry
             */
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/dashboard.html").setViewName("dashboard");
            }
            /**
             * 注册拦截器
             * @param registry
             */
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                // super.addInterceptors(registry);
                // 拦截任意路径下的所有请求, 排除请求
                registry.addInterceptor(new LoginHandlerInterceptor())
                        .addPathPatterns("/**")
                        .excludePathPatterns("/index.html", "/", "/user/login", "/static/**");
            }
        };
        return adapter;
    }
}

Restful CRUD

Rest 风格

URI: /资源/资源标识 HTTP 请求方式区分对资源 CRUD

image.png

员工列表-公共页抽取

公共片段抽取

<!-- 1、抽取公共片段 -->
<div th:fragment="copy">content</div>
<!-- 2、引入公共片段 -->
<div th:insert="~{footer::copy}">content</div>
<!-- 3、默认效果 -->
<!-- insert功能片段在div标签中 -->
~{templateName::selector} 模板名::选择器
~{templateName::fragmentName}模板名::片段名


3 种方式引入片段


th:insert 插入

th:replace 替换

th:include 引入片段内容


使用th:insert可以不写~{}

转义[[~{}]]

不转义[(~{})]


引入片段时候传入参数


链接高亮&列表完成


redirect 重定向

forward 转发


日期格式化


spring.mvc.format.date: yyyy-MM-dd


相关文章
|
4月前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
5779 79
|
4月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
4月前
|
算法 Java Go
【GoGin】(1)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
gin 框架中采用的路优酷是基于httprouter做的是一个高性能的 HTTP 请求路由器,适用于 Go 语言。它的设计目标是提供高效的路由匹配和低内存占用,特别适合需要高性能和简单路由的应用场景。
429 4
|
4月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
565 2
|
5月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
4590 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
713 0
|
5月前
|
安全 数据可视化 Java
AiPy开发的 Spring 漏洞检测神器,未授权访问无所遁形
针对Spring站点未授权访问问题,现有工具难以检测如Swagger、Actuator等组件漏洞,且缺乏修复建议。全新AI工具基于Aipy开发,具备图形界面,支持一键扫描常见Spring组件,自动识别未授权访问风险,按漏洞类型标注并提供修复方案,扫描结果可视化展示,支持导出报告,大幅提升渗透测试与漏洞定位效率。
|
6月前
|
前端开发 Java API
利用 Spring WebFlux 技术打造高效非阻塞 API 的完整开发方案与实践技巧
本文介绍了如何使用Spring WebFlux构建高效、可扩展的非阻塞API,涵盖响应式编程核心概念、技术方案设计及具体实现示例,适用于高并发场景下的API开发。
524 0
|
6月前
|
缓存 Java API
Spring WebFlux 2025 实操指南详解高性能非阻塞 API 开发全流程核心技巧
本指南基于Spring WebFlux 2025最新技术栈,详解如何构建高性能非阻塞API。涵盖环境搭建、响应式数据访问、注解与函数式两种API开发模式、响应式客户端使用、测试方法及性能优化技巧,助你掌握Spring WebFlux全流程开发核心实践。
1247 0