先看看目录结构,很简单的,一个控制器,一个拦截器,一个配置类,一个主类
拦截器类
package top.myico.sso.client.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author 夜色
* @version 1.0
* @date 2019/8/7 10:10
*/
public class ClientInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 获取session对象
HttpSession session = request.getSession();
// 查看session中是否存在uid
if (session.getAttribute("uid") != null){
// 有,放行
return true;
}
// 没有,重定向到CSDN
response.sendRedirect("https://www.csdn.net/");
// 拦截
return false;
}
}
配置类
package top.myico.sso.client.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.myico.sso.client.interceptor.ClientInterceptor;
/**
* @author 夜色
* @version 1.0
* @date 2019/8/7 10:51
*/
@Configuration
public class ClientInterceptorConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 创建拦截器
HandlerInterceptor interceptor = new ClientInterceptor();
// 添加黑名单(全部拦截)和白名单
registry.addInterceptor(interceptor)
// 黑名单——参数可以是List<String>或者String或者String...
.addPathPatterns("/**")
// 白名单——参数可以是List<String>或者String或者String...
.excludePathPatterns("/login");
}
}
控制类
package top.myico.sso.client.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
/**
* @author 夜色
* @version 1.0
* @date 2019/8/7 10:08
*/
@RestController
public class ClientController {
@RequestMapping("/main")
public String view() {
return "成功访问!";
}
@RequestMapping("/login")
public String login(HttpSession session, String username, String password){
// 验证账号密码(这里就不做了,假设验证通过了)
// 往session会话中加入uid
session.setAttribute("uid", "123");
return "登录成功!";
}
}
主类
package top.myico.sso.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author 夜色
* @version 1.0
* @date 2019/8/7 10:20
*/
@SpringBootApplication
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
运行项目,访问项目,我设置了端口是8081,默认是8080
跳到CSDN了
访问/login
登录成功
再访问/main就行了