当前位置:网站首页>Custom interceptor
Custom interceptor
2022-06-26 09:51:00 【Ma cute's Ma cute】
1、 The project structure is as follows

2、 The front-end code is as follows
<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')}"> chinese </a> <!--thymeleaf No need to ? This method takes the path variable @{/login.html?l='zh_CN'}-->
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
</form>
</body>
among method="post" Must write , Otherwise, even if the backend uses @PostMapping There will still be a reminder that the request method is wrong , Because the front end doesn't write method=“post”
For the code that displays the message <label style="color: red" th:text="${msg}"></label>, Use label Labels can be dispensed with if Statement to determine when a prompt message is displayed , Is it right to visit a certain page without logging in , Or the login account 、 The password is wrong !
3、 The back-end code is as follows
(1) Control view jump code
stay WebConfig implements WebMvcConfigurer Next rewrite WebMvcConfigurer Medium addViewControllers Method , Achieve the purpose of controlling view jump
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
(2) Provide service code
@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"; // Use redirect:/main.html To redirect to a virtual view , If you jump to template Under the dashboard The account and password will be displayed in the search box
}
else{
model.addAttribute("msg"," Wrong account or password ! Please login again !");
return "login"; // Jump directly to login page
}
}
}
(3)、 To write LoginHandlerInterceptor implements HandlerInterceptor file
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"," Please log in first !");
request.getRequestDispatcher("/").forward(request,response);
return false;
}
else {
return true;
}
}
}
(4)、 stay WebConfig implements WebMvcConfigurer Add your own defined interceptors in , Customize which static resources to intercept
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login.html","/index","/css/**","/js/**","/img/**");
}
4、WebConfig All the codes in are as follows
@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 // Register in container
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、 Demo login
Direct access main.html The path of , Prompt to log in first . Because I haven't logged in at this time ,session There is no login information in , So you can only access after logging in main.html The next path dashboard Front page 
After password login session There is loginUser Not empty , So you can access main.html The next path dashboard Front page 
边栏推荐
- PHP extracts TXT text to store the domain name in JSON data
- 【CVPR 2019】Semantic Image Synthesis with Spatially-Adaptive Normalization(SPADE)
- Notes on sports planning on November 22, 2021
- 自动化测试——pytest本身及第三方模块介绍及使用
- LeetCode 958. Completeness checking of binary tree
- Introduction to QPM
- 2021-11-12 vrep vision sensor configuration
- LeetCode 498. 对角线遍历
- 软件测试---如何选择合适的正交表
- 欧冠比赛数据集(梅西不哭-离开巴萨也可能再创巅峰)
猜你喜欢

Redis notes (14) - persistence and data recovery (data persistence RDB and AOF, data recovery, mixed persistence)

做测试需要知道的内容——url、弱网、接口、自动化、

深度学习(初识tensorflow2.版本)之三好学生成绩问题(1)

The 100000 line transaction lock has opened your eyes.

Mysql database field query case sensitive setting

Several connection query methods of SQL (internal connection, external connection, full connection and joint query)

Flutter's brain map notes are easy to find and search!

Curriculum learning (CL)

Badge series 4: use of circle Ci

How does flutter transfer parameters to the next page when switching pages?
随机推荐
软件测试---如何选择合适的正交表
Industrial and enterprise patent matching data (hundreds of thousands of data) 1998-2014
VI summary of common commands
Leetcode connected to rainwater series 42 (one dimension) 407 (2D)
Single sign on logic
Halcon photometric stereoscopic
Why do some functions in the go standard library have only signatures but no function bodies?
Throttling, anti chattering, new function, coriolism
A concise tutorial for getting started with go generics
[pulsar learning] pulsar Architecture Principle
Introduction to QPM
Thinking before QPM preparation optimization
2021-11-29 quintic polynomial of trajectory planning
2021-11-29 轨迹规划五次多项式
逻辑英语结构【重点】
Explained: A Style-Based Generator Architecture for GANs (StyleGAN)
Teach you to use shell script to check whether the server program is running
How to correctly open the USB debugging and complete log functions of Huawei mobile phones?
Differences between VI and vim and common commands
pcl install