SprintBoot小实战

本文介绍了如何在Spring Boot项目中整合Thymeleaf,实现页面国际化,并通过自定义拦截器进行登录状态检查。首先,详细讲述了配置Thymeleaf的步骤,包括引入依赖、配置国际化文件以及在页面中使用国际化标签。接着,展示了登录检查拦截器的实现代码,用于拦截未登录用户的请求并重定向到登录页面。最后,演示了如何注册拦截器以保护特定的URL路径。
摘要由CSDN通过智能技术生成

一、国际化

前提准备:

1.导入thymeleaf依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
              2.1.6
        </dependency>
切换thymeleaf版本
<properties>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
        <!-- thymeleaf2   layout1-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>

2.Thymeleaf使用(基础+核心)

2.1 导入thymeleaf的名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2.2thymeleaf语法

${...}

 1、获取对象的属性、调用方法
 2、使用内置的基本对象:
 3、内置的一些工具对象:

 *{...}  选择表达式:和${}在功能上是一样

#{...}:获取国际化内容

 @{...}:定义URL

.........

操作:

1.配置文件 

新建 resources/il8n

注意:application.propertise需要加此配置文件,因为默认配置路径不是这

 随便点击一个il8n下的properties文件 


注意:file encodings 为UTF-8,无论是全局还是项目部署 

2.去页面获取国际化的值

对应之前设置的参数

例如:

<label class="sr-only" ">Username</label>

改为:

<label class="sr-only" th:text="#{login.username}">Username</label>

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta name="description" content="">
		<meta name="author" content="">
		<title>Signin Template for Bootstrap</title>
		<!-- Bootstrap core CSS -->
		<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
		<!-- Custom styles for this template -->
		<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
	</head>

	<body class="text-center">
		<form class="form-signin"   th:action="@{/login}" method="post">
			<img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:src="@{asserts/img/bootstrap-solid.svg}"  alt="" width="72" height="72">
			<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>

			<!-- 错误信息显示 -->
			<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>


			<label class="sr-only" th:text="#{login.username}">Username</label>
			<input type="text" class="form-control" name="username" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">

			<label class="sr-only" th:text="#{login.password}">Password</label>

			<input type="password" class="form-control" th:placeholder="#{login.password}" name="password" placeholder="" required="">
			<div class="checkbox mb-3">
				<label>
          <input type="checkbox" value="remember-me" > [[#{login.remember}]]
        </label>
			</div>
			<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
			<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
			<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
		</form>

	</body>

</html>

3.点击链接切换国际化

创建一个自己的MyLocaleResolver

二、拦截器进行登陆检查

/**
 * 登陆检查,
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public 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 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 {

    }
}

注册拦截器

 //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }

            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/","/user/login");
            }
        };
        return adapter;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值