当前位置:网站首页>定制拦截器
定制拦截器
2022-06-26 09:34:00 【马可爱家的马可爱】
1、项目结构如下

2、前端代码如下
<body class="text-center">
<form class="form-signin" method="post" th:action="@{/index}">
<img class="mb-4" th:src="@{/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 style="color: red" th:text="${msg}"></label>
<label class="sr-only">Username</label>
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</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> <!--thymeleaf中不用?这种方式取路径变量@{/login.html?l='zh_CN'}-->
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
</form>
</body>
其中 method="post"必须写,否则即使后端使用@PostMapping依然会出现请求方式错误的提醒,因为前端没有写 method=“post”
其中对于显示消息的代码 <label style="color: red" th:text="${msg}"></label>,使用label标签可以不用if语句判断什么时候显示提示消息,到底是没有登陆就访问某一页面了,还是登陆的账号、密码有误!
3、后端代码如下
(1)控制视图跳转代码
在WebConfig implements WebMvcConfigurer下重写WebMvcConfigurer中的addViewControllers方法,达到控制视图跳转的目的
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
(2)提供服务代码
@Controller
public class Admin {
@PostMapping("/index")
public String index(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session){
if(!StringUtils.isEmpty(username)&& "ml".equals(username) &&!StringUtils.isEmpty(password)&& "123".equals(password)){
session.setAttribute("loginUser",username);
return "redirect:/main.html"; //使用redirect:/main.html是为了重定向到到虚拟的视图,如果跳转到template下的dashboard会在搜索框显示账号密码
}
else{
model.addAttribute("msg","账号或者密码有误!请重新登陆!");
return "login"; //直接跳转到login页面
}
}
}
(3)、编写LoginHandlerInterceptor implements HandlerInterceptor文件
package com.ma.ml.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser==null){
request.setAttribute("msg","请先登陆!");
request.getRequestDispatcher("/").forward(request,response);
return false;
}
else {
return true;
}
}
}
(4)、在WebConfig implements WebMvcConfigurer 中添加自己定义好的拦截器,定制拦截哪些静态资源
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login.html","/index","/css/**","/js/**","/img/**");
}
4、WebConfig中的所有代码如下
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
@Bean //注册到容器中
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login.html","/index","/css/**","/js/**","/img/**");
}
}
5、演示登陆
直接访问main.html的路径,提示要先登陆。因为此时没有登陆过,session中没有登陆信息,所以只有登陆之后才可以访问main.html路径下的dashboard前端页面
密码登陆之后session中有了loginUser不为空,所以可以访问main.html路径下的dashboard前端页面
边栏推荐
- mysql 数据库字段查询区分大小写设置
- VI summary of common commands
- c语言语法基础之——函数定义学习
- Redis notes (16) - info instructions and command line tools (view memory, status, number of client connections, monitoring server, scan large keys, sampling server, execute batch commands, etc.)
- LeetCode 接雨水系列 42.(一维) 407.(二维)
- Origin of QPM
- QPM performance monitoring components - General
- Leetcode connected to rainwater series 42 (one dimension) 407 (2D)
- PHP does not allow images to be uploaded together with data (no longer uploading images before uploading data)
- [Journal of Computer Aided Design & computer graphics] overview of research on pedestrian re recognition methods based on generated countermeasure network
猜你喜欢

Mysql database field query case sensitive setting

DAY 3 数组,前置后置,字符空间,关键词和地址指针

How does flutter transfer parameters to the next page when switching pages?

Redis notes (13) - scan and keys search for specific prefix key fields (command format, usage examples, locating large keys)

Redis notes (12) - single thread architecture (non blocking IO, multiplexing) and multiple asynchronous threads

Thinkphp5 manual error reporting

工企专利匹配数据(数十万数据量)1998-2014年
Optimization of power assisted performance of QPM suspended window

How to create an IE tab in edge browser

Wechat official account reported error 10003
随机推荐
A Style-Based Generator Architecture for Generative Adversarial Networks
Badge series 7: use of codacy
How about the security of flush stock trading software? How to open an account in flush
教你用shell脚本检测服务器程序是否在运行
Opencv depthframe - > pointcloud causes segmentation fault!
安装 新版本cmake & swig & tinyspline
I am in Zhongshan. Where can I open an account? Is online account opening safe?
Collection object replication
MapReduce & yarn theory
jz2440---使用uboot燒錄程序
Badge collection 6:api\_ Use of level
mysql 数据库字段查询区分大小写设置
Thinkphp5 manual error reporting
使用递归或while循环获取父/子层级结构的名称
Flutter's brain map notes are easy to find and search!
【CVPR 2019】Semantic Image Synthesis with Spatially-Adaptive Normalization(SPADE)
#云原生征文# 在 Google Kubernetes Cluster 上使用 HANA Expression Database Service
Redis novice introduction
Regular expression learning
Comparison of similar PMS in QPM