目录
1. 导入静态资源和配置默认页面
在网上随便找一个登录页面稍作修改,添加两个a标签,用于切换语言。我的页面效果如下:
注:我这里是直接将登录页面命名为index.html,springboot能帮我找到这个默认首页,但如果我将index.html改为login.html后,springboot就找不到默认的首页了,这个时候我们就需要写一个配置类,来添加一个视图解析器,将默认请求发送到login,这个时候需要用到模板引擎,具体操作入下:
pom文件中引入Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然后将index.html改名为login.html,放在Thymeleaf默认的文件夹templates中:
并修改页面的静态资源引用路径,采用thymeleaf语法进行替换,不然静态资源引用不成功。
接下来编写一个配置类,用于将默认请求定位到login.html页面。
package com.chtw.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;
/**
* 设置默认页面
* @author CHTW
* @date 2019-10-15-9:12
*/
@Configuration
public class myConfig extends 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");
}
};
return adapter;
}
}
然后启动服务器,看看能否出现登录页面:
这样就说明我们配置的默认页面成功了。下面进行页面国际化。
2. 页面国际化
简单的来说,国际化就是不改变页面的代码,能够切换页面的语言,使用英语,使用中文,当然也可以是其他的语言。国际化的方法也有很多,到目前为止,我也只学了一种方法。采用的I18N来实现国际化。I18N有一个好处就是他能实现任何网站的国际化,并且反应迅速。i18n的命名规范可以参考:i18n命名规范
2.1 编写国际化配置文件
login.properties
login.btn=登录
login.username=用户名
login.password=密码
login.h1=用户登录
login_en_US.properties
login.btn=login
login.username=username
login.password=password
login.h1=UserLogin
login_zh_CN.properties
login.btn=登录
login.username=请输入用户名
login.password=密码
login.h1=用户登录
2.2 管理国际化资源文件
SpringBoot自动配置好了管理国际化资源文件的组件; 可以查看这个类:MessageSourceAutoConfiguration里面的messageSource。我们只需要指定一下基础名,这个组件就能自动识别国家化资源文件。在application.properties中添加:
spring.messages.basename=i18n/login
2.3 页面获取国际化值
在login.html中修改相应的标签默认值,采用thymeleaf语法进行替换
这个时候,我们点击的时候不能进行切换,只能根据浏览器的语言设置进行转换。
Springboot进行国际化的原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);
他是从浏览器的请求头部中获取区域信息进行国家化的,比如在中文情况下,F12查看
那么我们就可以在点击的时候带上一个请求参数
再重新编写一个区域信息解析器LocaleResolver
package com.chtw.component;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
/**
* @author CHTW
* @date 2019-10-15-10:25
*/
@Configuration
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("language");
System.out.println(language);
Locale locale = Locale.getDefault();
if (!StringUtils.isEmpty(language)) {
String[] split = language.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
//将我们的区域解析器放在容器中
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
}
再启动服务器,点击就能够进行切换语言了。
3. 登录拦截器
在实际开发者,登录拦截器也是不可少的一部分,不过不进行登录也能直接访问后台页面,那么登录这个功能也就没用存在价值了,这种做法也非常危险的。
修改最终的login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>登录</title>
<link rel="stylesheet" type="text/css" th:href="@{/css/style.css}" href="../static/css/style.css">
<script type="text/javascript" th:src="@{/js/jquery.min.js}" src="../static/js/jquery.min.js"></script>
<script type="text/javascript" th:src="@{/js/vector.js}" src="../static/js/vector.js"></script>
</head>
<body>
<div id="container">
<div id="output">
<div class="containerT">
<h1 th:text="#{login.h1}">用户登录</h1>
<p style="color: red;margin-top: 15px;font-size: 16px;" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<form class="form" id="entry_form" action="/login" method="post">
<input type="text" th:placeholder="#{login.username}" placeholder="用户名" name="username" id="entry_name">
<input type="password" th:placeholder="#{login.password}" placeholder="密码" name="password" id="entry_password">
<input type="submit" th:value="#{login.btn}" id="entry_btn"/>
<div style="margin-top: 10px;">
<a th:href="@{/index.html?language=zh_CN}" style="margin-right:15px; ">中文</a>
<a th:href="@{/index.html?language=en_US}">English</a>
</div>
<div id="prompt" class="prompt"></div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
Victor("container", "output"); //登录背景函数
$("#entry_name").focus();
$(document).keydown(function(event){
if(event.keyCode==13){
$("#entry_btn").click();
}
});
});
</script>
</body>
</html>
新建一个suss.html作为登录成功的提示页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录成功</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
新建一个LoginInterceptor作为登录拦截器
package com.chtw.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author CHTW
* @date 2019-10-15-10:50
*/
public class LoginInterceptor 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 {
}
}
将拦截器添加到容器中,修改MyConfig类
package com.chtw.config;
import com.chtw.interceptor.LoginInterceptor;
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;
/**
* @author CHTW
* @date 2019-10-15-9:12
*/
@Configuration
public class myConfig extends 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("suss");
//为了防止数据重复提交,登录成功后我们将页面重定向到main.html这个请求,这里添加一个视图解析器,将mian.html定位到suss.html
}
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//super.addInterceptors(registry);
//静态资源; *.css , *.js
//SpringBoot已经做好了静态资源映射
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/css/*","/js/*","/login");
/*
* addPathPatterns设置拦截路径
* excludePathPatterns设置不拦截的路径
*/
}
};
return adapter;
}
}
controller层
package com.chtw.controller;
import com.chtw.entity.People;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @author CHTW
* @date 2019-08-23-17:43
*/
/*
* @Controller
* @ResponseBody
*/
@Controller
public class HelloController {
@Autowired
private People people;
@ResponseBody
@RequestMapping("/hello")
public String hello(){
System.out.println(people.toString());
return "Hello World! Welcome to Spring-Boot"+people.toString();
}
@RequestMapping("/login")
public String login(HttpServletRequest request, HttpSession session,Model model){
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.equals("admin")&&password.equals("admin")){
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else{
model.addAttribute("msg","用户或密码错误!");
return "login";
}
}
}
启动服务器,当我们直接访问main.html的时候,就会出现以下情况说明拦截成功:
本节类容到此结束
本人联系方式2329095893,欢迎各位进行学习讨论
欢迎关注熊熊出没ING公众号,不定时跟新Java、python、信息安全等相关知识哦。