SpringBoot Web开发(5) 开发页面国际化+登录拦截

一、页面国际化

页面国际化目的:根据浏览器语言设置的信息对页面信息进行切换,或者用户点击链接自行对页面语言信息进行切换。

**效果演示:**当浏览器语言设置为英文优先时,或者用户点击页面“English”选项时,页面如下图所示:

当浏览器语言设置为中文优先时,或者用户点击页面“中文”选项时,页面如下图所示:

下面说说具体的实现步骤及实现原理:

一、编写国际化配置文件,抽取页面需要显示的国际化消息

在resources资源文件夹下创建“i18n”国际化文件夹,在其中编写国际化配置文件。

二、SpringBoot自动配置好了管理国际化资源文件的组件,部分源码如下:

@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
private static final Resource[] NO_RESOURCES = new Resource[0]; public MessageSourceAutoConfiguration() {
} @Bean
@ConfigurationProperties(
prefix = "spring.messages"
) .....
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
//设置国际化资源文件的基础名(去掉语言国家代码的)
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
} if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
} messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
} messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
}

三、在application.properties中配置国际化文件夹的路径

spring.messages.basename=i18n.login

四、在页面上获取国际化的值

<!DOCTYPE html>
<!--引入Thymeleaf模板名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link href="favicon.ico" rel="shortcut icon">
<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 -->
<!--把webjars的bootstrap框架引进来解析Thymeleaf模板-->
<link href="asserts/css/bootstrap.min.css" th:href="@{webjars/bootstrap/4.2.1/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<!--使用Thymeleaf模板引擎把自定义的界面样式引进来-->
<link href="asserts/css/signin.css" th:href="@{asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html" th:action="@{/user/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>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" 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="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
</form>
</body>
</html>

五、根据浏览器语言设置信息切换国际化 (springboot已经自动配置好了)

国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);

部分源码如下:

public class WebMvcAutoConfiguration {
....
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
} else {
//默认的就是根据请求头带来的区域信息获取Locale进行国际化
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
}
...
} public class AcceptHeaderLocaleResolver implements LocaleResolver {
......
public Locale resolveLocale(HttpServletRequest request) {
Locale defaultLocale = this.getDefaultLocale();
if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
return defaultLocale;
} else {
//根据浏览器的请求头,(即浏览器语言设置)切换国际化
Locale requestLocale = request.getLocale();
List<Locale> supportedLocales = this.getSupportedLocales();
if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
if (supportedLocale != null) {
return supportedLocale;
} else {
return defaultLocale != null ? defaultLocale : requestLocale;
}
} else {
return requestLocale;
}
}
}
....
}

六、实现点击链接切换国际化

A、设置点击链接时,传递语言设置信息到后端

			<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>

B、配置区域信息解析器,重写resolveLocale(HttpServletRequest httpServletRequest)方法

/**
* 可以在链接上携带区域信息
*/
public class MyLocalResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l = httpServletRequest.getParameter("l");
// Locale locale = Locale.getDefault();
Locale locale =httpServletRequest.getLocale(); //默认根据浏览器语言设置切换国际化信息
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { }
}

C、配置视图解析器,然后把配置好的区域信息解析器添加到容器中

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
}

二、登录拦截

登录拦截目的:阻止直接访问某些不可直接访问的界面。(比如登录教务系统才可查看学生成绩,不可直接访问学生成绩界面)。

场景:未进入登录界面登录,通过链接直接访问登录后可见的页面。

设置登录拦截前:(直接在未登录状态进入管理系统)

设置登录拦截后:(在未登录状态进入登录系统时拦截请求并跳转到登录页面给出相应的提示)

下面说说具体的实现步骤及实现原理:

一、默认登录首页

设置默认登录首页的两种方式:

a.使用@Controller的方式

@Controller
public class LoginController {
@RequestMapping("/")
public String login(){
return "login";
}
}

b.编写写配置类,通过addViewControllers添加跳转映射

@Configuration
public class WebMvcConfig implements WebMvcConfigurer { @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
}

二、设置登录拦截功能

开发期间模板引擎页面修改以后,要使页面实时生效就要禁用模板引擎缓存。

在application.properties文件中做如下配置:

#禁用缓存
spring.thymeleaf.cache=false

页面修改完成以后按ctrl+f9:重新编译页面信息;(不用重新启动项目使得更改生效)

登陆错误消息的显示:

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

A、编写登录控制器

@Controller
public class LoginController {
@PostMapping(value = "/user/login")
//@RequestParam明确是从请求参数中获取值
//httpSession是存放登录过的用户信息,用户登录过以后就在session中存在
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map, HttpSession session){
if(!StringUtils.isEmpty(username) && "123456".equals(password)){
//登陆成功,防止表单重复提交,可以重定向到主页
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else{
//登陆失败
map.put("msg","用户名密码错误");
return "login";
}
}
}

B、编写登录拦截器进行登录检查

/**
* 登陆检查,
*/
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("/login.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 {
}
}

C、注册拦截器

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**") .excludePathPatterns("/login.html","/","/user/login","/asserts/**","/webjars/**");
} //此处要放行css js等静态资源文件
}

SpringBoot Web开发(5) 开发页面国际化+登录拦截的更多相关文章

  1. chrome拓展开发实战:页面脚本的拦截注入

    原文请访问个人博客:chrome拓展开发实战:页面脚本的拦截注入 目前公司产品的无线站点已经实现了业务平台组件化,所有业务组件的转场都是通过路由来完成,而各个模块是通过requirejs进行统一管理, ...

  2. WEB开发----springboot的登录拦截机制

    如果是一个后台的管理项目的,有些东西是不能直接就可以访问的,必须要登录才可以进去,所以就需要进行登录拦截,只有登录过的用户才可以正常访问. 登录拦截是不会拦截jsp页面的方法,所以我们需要在Contr ...

  3. SpringBoot Web开发(4) Thymeleaf模板与freemaker

    SpringBoot Web开发(4) Thymeleaf模板与freemaker 一.模板引擎 常用得模板引擎有JSP.Velocity.Freemarker.Thymeleaf SpringBoo ...

  4. 【SpringBoot】SpringBoot Web开发(八)

    本周介绍SpringBoot项目Web开发的项目内容,及常用的CRUD操作,阅读本章前请阅读[SpringBoot]SpringBoot与Thymeleaf模版(六)的相关内容 Web开发 项目搭建 ...

  5. 【SpringBoot基础系列】手把手实现国际化支持实例开发

    [SpringBoot基础系列]手把手实现国际化支持实例开发 国际化的支持,对于app开发的小伙伴来说应该比价常见了:作为java后端的小伙伴,一般来讲接触国际化的机会不太多,毕竟业务开展到海外的企业 ...

  6. springboot web开发【转】【补】

    pom.xml引入webjars的官网 https://www.webjars.org/ https://www.thymeleaf.org/doc/tutorials/3.0/usingthymel ...

  7. JAVA WEB开发中的资源国际化

    为什么要国际化? 不同国家与地区语言,文化,生活习惯等差异.在数字,时间,语言,货币,日期,百分数等的不同. 两个名词: I18N:即资源国际化,全称为Internationalization,因为首 ...

  8. 基于SpringBoot从零构建博客网站 - 开发文章详情页面

    文章详情页面是博客系统中最为重要的页面,登录用户与游客都可以浏览文章详情页面,只不过只有登录用户才能进行其它的一些操作,比如评论.点赞和收藏等等. 本次的开发任务只是将文章详情页面展示出来,至于一些收 ...

  9. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_5-10.Springboot2.x用户登录拦截器开发实战

    笔记 10.Springboot2.x用户登录拦截器开发实战     简介:实战开发用户登录拦截器拦截器 LoginInterceptor                  1.实现接口 LoginI ...

随机推荐

  1. dedecmsv5.7 前台模版里输出变量

    如何在PHP文件查询出来的数据赋值给前端页面展示出来? 例如: PHP文件:agency.php require_once(dirname(__FILE__) . '/../../include/co ...

  2. 『计算机视觉』Mask-RCNN_训练网络其三:训练Model

    Github地址:Mask_RCNN 『计算机视觉』Mask-RCNN_论文学习 『计算机视觉』Mask-RCNN_项目文档翻译 『计算机视觉』Mask-RCNN_推断网络其一:总览 『计算机视觉』M ...

  3. python自动化测试入门篇-jemter连接mysql数据库

    jmeter对数据库的操作主要包括以下几个步骤:1.导入mysqlde jdbc的jar包:2.创建数据库连接配置:3.线程组添加jdbc request;4.启动按钮,添加查看结果树 一.准备好驱动 ...

  4. 在500jsp错误页面获取错误信息

    自定义异常发生时的错误处理页面: 1) 只要定义page指示元素的errorPage属性就可以指定当前页面发生异常时应该交给哪个页面进行处理,例如:<%@page errorPage=" ...

  5. 佛祖保佑永无BUG代码注释

    // // _oo0oo_ // o8888888o // 88" . "88 // (| -_- |) // 0\ = /0 // ___/`---'\___ // .' \\| ...

  6. 监听图片src发生改变时的事件

    $img.on('load', function() { $img.attr("src", getBase64Image($img.get(0))); $img.off('load ...

  7. 朋友给的IE滚动条

    scrollbar-arrow-color: #f4ae21;  /*图6,三角箭头的颜色*/scrollbar-face-color: #333;  /*图5,立体滚动条的颜色*/scrollbar ...

  8. python项目练习

    程序框图 (消费模块暂未写入) bin:程序执行 import os import sys base_dir = os.path.dirname(os.path.dirname(os.path.abs ...

  9. 微信https抓包,不同安卓版本、微信版本对证书的要求

    安卓系统 7.0 以下版本,不管微信任意版本,都会信任系统提供的证书 安卓系统 7.0 以上版本,微信 7.0 以下版本,微信会信任系统提供的证书 安卓系统 7.0 以上版本,微信 7.0 以上版本, ...

  10. 关于NOIP复赛规模的规定

    近年来NOIP初赛参赛人数不断增长,复赛规模也相应扩大,但仍不能满足选手积极参赛及扩大普及面的需求,现对NOIP复赛规模的规则调整如下. 1.每个省赛区可以设立多于两个的复赛考点,但必须在同一个城市, ...