SpringBoot+thymeleaf实现视图控制器,拦截器,国际化功能

  • 注意:
    1、配置视图控制器要添加web依赖,视图跳转到templates包下的页面需要添加thymeleaf依赖
    2、thymeleaf模板引擎默认扫描templates包下的页面,且默认后缀名为.html所以我们可以不用加后缀名。
    3、所有页面的静态资源度需要thymeleaf来接管:@{}。导入别人的页面时,要引入thymeleaf模板引擎的头文件(命名空间)才会在HTML页面中加载static中的样式,(thymeleaf默认从static包中找样式,页面样式引入需要采用thymeleaf语法才能生效@{/static文件下的路径})
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    4、如果样式没有生效可能是thymeleaf缓存的问题,需要在主配置文件中关闭缓存spring.thymeleaf.cache = false
    5、springboot自动帮我们进行了配置,当程序出现错误后,会自动找到error文件下的错误页面

一、视图控制器

1)视图控制器:作用可以集中控制前端发送跳转页面的请求并返还指定视图。(即所有直接跳转页面的请求都可在视图控制器中配置)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

配置视图控制器我们需要带入web依赖,实现WebMvcConfigurer接口并重写addViewControllers()方法

在这里插入图片描述

//配置mvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    //配置视图控制  我们初始化视图
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login"); //访问路径时/时,跳转到登录页面
        registry.addViewController("/index").setViewName("index");  //访问路径是/index时,跳转到index首页
        registry.addViewController("/error").setViewName("error");  //访问路径是/error时,跳转到error首页
    }

2)视图解析器:SpringBoot自动为Thymealf注册了一个视图解析器ThymealfViewResolver,并且配置了模板(HTML)的位置,与JSP类似的前缀+视图名+后缀的风格。我们可以进到它的配置文件(ThymeleafProperties)里去看:thymeleaf模板引擎默认扫描templates包下的页面,且默认后缀名为.html所以我们可以不用加后缀名。

在这里插入图片描述

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、拦截器

拦截器作用:拦截器可以对请求的所有路径进行拦截和放行。防止用户通过地址栏直接访问页面。

1)自定义拦截器,配置拦截规则:实现HandlerInterceptor接口重写preHandle预处理方法,获取session中的用户,判断是否登录过,有值即登录过可放行,为null即没登录过,重定向到登录页面。

在这里插入图片描述

//自定义拦截器:实现拦截器接口,重写预处理方法
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("user"); //判断是否登录,登录后session中存有用户 return true放行 return false 拦截
        if (user == null) {
             response.sendRedirect("/login"); //重定向到登录页面
             return false;
        } else {
            return true;
        }
    }
}

2)添加拦截器:自定义了拦截器之后,还需要将拦截器添加到SpringBoot配置中,在实现了WebMvcConfigurer的类中重写添加拦截器方法addInterceptors,拦截所有路径并排除登录访问路径,和一些静态资源路径。

在这里插入图片描述

  //添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**") //拦截所有资源
                .excludePathPatterns("/login","/","/error","/css/*","/images/**","/js/**","/lib/**"); //不拦截资源路径,登录路径,静态资源路径
    }

三、theymeleaf国际化

spring boot 会根据请求头中的 区域信息自动的选择语言

效果图:

在这里插入图片描述
如果将浏览器的语言切换到英语会看到图示效果

在这里插入图片描述

在SpringBoot项目里面做国际化,只需要在resources/i18n路径下创建xxx.properties、xxx_en_US.properties、xxx_zh_CN.properties即可。具体怎么做,将在下文进行演示。
在SpringBoot中有一个messageSourceAutoConfiguration,它会自动管理国际化资源文件。

在这里插入图片描述
也就是说,我们在resources/i18n创建的国际化配置文件前缀名为message时,SpringBoot会自动加载。

在这里插入图片描述
当然,我们也可以自己定义国际化文件名称,这里我们将国际化配置文件命名为login。
1、去yml配置文件中配置国际化

spring
  messages: i18n.login

2、要确保文件编码是UTF-8,可以到idea的设置里去设置并让其自动转换,Editor->File Encodings

在这里插入图片描述
3、创建i18n文件夹及3个国际化配置文件,如图
其中login.properties是基础配置文件(默认),如果你的浏览器它是其他语言比如法语,是没有办法国际化的,所以它就会采用login.properties

在这里插入图片描述
在idea里只要创建两个国际化的配置文件就会自动加入到Resource Bundle ‘xxx’,当然我们还是需要创建三个properties配置文件。后缀必须按格式写,_en_US就是英文,_zh_CN就是中文。

4、编写国际化
我们直接点进login.properties,可以看到下方有个切换到Resource Bundle的按钮,点击切换,添加国际化,然后分别在右侧写上对应国际化语言
在这里插入图片描述
想添加多少,就可以添加多少。
5、可以在Thymeleaf页面进行获取了,用到thymeleaf语法中的获取国际化语言标签 #{}

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

6、一般来说我们在页面会做个切换中英文的按钮来进行切换

<a th:href="@{/login(lan='zn_CN')}">中文</a>
<a th:href="@{/login(lan='en_US')}">英文</a>

实例代码:

<!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">
  <title>用户登录界面</title>
  <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
  <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<!--  用户登录form表单 -->
<form class="form-signin">
  <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
  <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}" >请登录</h1>
  <input type="text" class="form-control"
         th:placeholder="#{login.username}"  required="" autofocus="">
  <input type="password" class="form-control"
         th:placeholder="#{login.password}"  required="">
  <div class="checkbox mb-3">
    <label>
      <input type="checkbox" value="remember-me">[[#{login.rememberme}]]
    </label>
  </div>
  <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}" >登录
  </button>
  <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}" >2018</span>-<span
          th:text="${currentYear}+1">2019</span></p>
  <a class="btn btn-sm" th:href="@{/login(l='zh_CN')}" >中文</a>
  <a class="btn btn-sm" th:href="@{/login(l='en_US')}">English</a>
</form>
</body>
</html>

7、做完上诉步骤,我们还需要编写一个本地解析器来进行解析

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 接收语言的参数 - 传进来的就是形如'zh_CN'这样的参数
        String lan = request.getParameter("lan");
        // 使用默认的语言 - 在文中就是login.properties文件里配置的
        Locale locale = Locale.getDefault();
        // 判断接收的参数是否为空,不为空就设置为该语言
        if(!StringUtils.isEmpty(lan)){
            // 将参数分隔 - 假设传进来的是'zh_CN'
            String[] s = lan.split("_");
            // 语言编码:zh   地区编码:CN
            locale = new Locale(s[0],s[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

8、我们在配置文件中注入我们自定义的国际化解析器

在这里插入图片描述

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	@Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

国际化就这样完成了,通过上面定义的切换语言按钮就可以切换了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值