项目记录1-(拦截器)

5.后台管理:

5.1登录

1.构建登录页面和后台管理首页

2.UserService和UserRepository

3.LoginController实现登录

4.MD5加密

5.登录拦截器

(凡是有关admin路径的,都要找张网拦截起来)

用springboot里面内置的interceptor

用HanderIntercepterAdapter,内置适配器

用preHandel,在请求到达之前进行拦截预处理

代码:

Logininterceptor:

package com.xpp2.blog2.interceptor;

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

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

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(request.getSession().getAttribute("user")==null){
            response.sendRedirect("/admin");
            return false;
        }
       return true;///继续执行就好了
    }
}

 

WebConfig:

package com.xpp2.blog2.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }
}

 

发布了575 篇原创文章 · 获赞 111 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/xianpingping/article/details/105136116