Spring Boot中Interceptor的使用-登录案例

当我们直接在浏览器输入某些URL时,比如我的账号,如果用户没有登录,应该直接跳转至登录页面,登录成功后进入我的账号页面;如果用户已经登录的情况下,点击我的账号,直接进入我的账号页面。这种情况我们可以使用Interceptor来实现,下面是Spring Boot中Interceptor的案例。

  1. 新建Spring Boot项目,dependency spring-boot-starter-web
  2. 实现我的账号功能页面
  3. 新建类RequiredHardLoginInterceptor,代码如下:
package com.oneonone.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.oneonone.entities.Customer;

public class RequiredHardLoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		Customer customer = (Customer)request.getSession().getAttribute("user");
		if(customer != null) {//已经登陆
			return true;
		}
			
		//没有登陆,转到登陆页面
		String url = request.getRequestURI();
		response.sendRedirect("/login?next=".concat(url));
		return false;
	}
	
}

  1. 新建配置类InterceptorsConfig,代码如下:
    package com.oneonone.commons;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.oneonone.interceptors.RequiredHardLoginInterceptor;

@Configuration
public class InterceptorsConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new RequiredHardLoginInterceptor())
            .addPathPatterns("/account/**").addPathPatterns("/checkout/**");
}

}

推荐视频
玩转Spring Data JPA&Spring Data JDBC

深入浅出SpringCloud

SpringBoot快速入门

Spring MVC快速开发

轻松搞定Spring全家桶(初识篇)

玩转Spring全家桶

推荐文章

系统上线后雪崩!让我们来学习 Spring Cloud Hystrix 及监控来解决雪崩问题

10 分钟教会你 Spring Boot 集成 Thymeleaf、MyBatis 完成产品的增删改查

【高阶用法】一个实例学会 Spring Cloud 的注册中心 Eureka的使用

Spring Cloud gateway与注册中心Eureka的完美集成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码界领航

你的鼓励将是我最最大的创作动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值