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. 关于vs code 快速生成vue 模板

    在 文件>首选项>用户代码片断里面,打开vue.json 添加以下代码: "Print to console": { "prefix": " ...

  2. PHP文件PHP代码及运行(适合PHP初学者)

    本文转自:https://blog.csdn.net/cnds123/article/details/80700444 如果在warmpserver上运行php只显示源代码,可能是在用记事本保存后缀为 ...

  3. linux服务管理 服务启动和自启动

    服务启动和自启动 '服务启动' 就是在当前系统中让服务运行,并提供功能 '服务自启动' 自启动是指服务在系统开机或重启动之后,随着启动系统的启动而自动启动服务 服务自启动 [root@ssgao198 ...

  4. 版本管理工具Git(3)VS2013下如何使用git

    Git系列导航 版本管理工具Git(1)带你认识git 版本管理工具Git(2)git的安装及使用 版本管理工具Git(3)VS下如何使用git VS下创建项目 vs中新建项目MyGitTest201 ...

  5. 跟随我在oracle学习php(6)

    CSS,主要用于控制Web页面的外观.通过使用CSS样式设置页面的风格,可将页面的内容 与表现形式分离.css  层叠样式表美化页面配合html布局. 在当前可以浏览的网站当中,都存在着CSS样式代码 ...

  6. yii2 中excel表导出

    首先下载phpexcel 在引入类文件(在web中index.php入口文件或者控制器中引入) require_once dirname(dirname(__FILE__)).'/excel/PHPE ...

  7. [Leetcode 134]汽车加油站 Gas Station (环形)

    [题目] There are N gas stations along a circular route, where the amount of gas at station i is gas[i] ...

  8. 使用Git上传项目到Gitee

    参考原文链接为:https://blog.csdn.net/qq944639839/article/details/79864081 1.打开GitBash 2. cd Client //进入工程目录 ...

  9. Alpha 冲刺11——总结

    拖鞋旅游队团队事后诸葛亮会议 前言 队名:拖鞋旅游队 组长博客:https://www.cnblogs.com/Sulumer/p/10054510.html 时间:2018-12-1 20:00 地 ...

  10. python自动化运维os语法

    得到当前工作目录,即当前Python脚本工作的目录路径:os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 递归查询指定路径下的所有文件和目录:os.walk() 函数 ...