当前位置:网站首页>定制拦截器
定制拦截器
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单表500万条数据增、删、改、查速度测试
- mysql 数据库字段查询区分大小写设置
- What you need to know to test -- URL, weak network, interface, automation
- Learning to Generalize Unseen Domains via Memory-based Multi-Source Meta-Learning for Person Re-ID
- Jz2440--- using uboot burning program
- Why do some functions in the go standard library have only signatures but no function bodies?
- OpenCV depthframe -> pointcloud 导致 segmentation fault!
- The first techo day Tencent technology open day, 628
- VI summary of common commands
- Thinkphp5 manual error reporting
猜你喜欢
安装 新版本cmake & swig & tinyspline
欧冠比赛数据集(梅西不哭-离开巴萨也可能再创巅峰)
【CVPR 2019】Semantic Image Synthesis with Spatially-Adaptive Normalization(SPADE)
jz2440---使用uboot燒錄程序
Champions League data set (Messi doesn't cry - leaving Barcelona may reach another peak)
Go learning notes (83) - code specification and common development skills
Force buckle ----- remove the maximum and minimum values from the array
logback
What you need to know to test -- URL, weak network, interface, automation
install opencv-contrib-dev to use aruco code
随机推荐
Enter the page input box to automatically obtain the focus
Does the go compiled executable have dynamic library links?
halcon 光度立体
I am in Zhongshan. Where can I open an account? Is online account opening safe?
online trajectory generation
Detailed explanation of the network security competition questions (2) of the 2021 national vocational college skills competition (secondary vocational group)
Notes on sports planning on November 22, 2021
QPM performance monitoring components - General
jz2440---使用uboot燒錄程序
Logical English structure [key points]
我在中山,到哪里开户比较好?在线开户安全么?
Collection object replication
做测试需要知道的内容——url、弱网、接口、自动化、
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.)
SQL advanced tutorial
A concise tutorial for getting started with go generics
online trajectory generation
安装 新版本cmake & swig & tinyspline
Redis notes (12) - single thread architecture (non blocking IO, multiplexing) and multiple asynchronous threads
Comparison of similar PMS in QPM