springboot拦截

本文详细介绍了如何在SpringBoot项目中设置一个拦截器,以保护未登录用户的访问,通过验证用户身份并记录操作,确保只有登录用户能访问管理界面。涉及Controller、数据库操作和HandlerInterceptor的使用。
摘要由CSDN通过智能技术生成

springboot项目实现登陆拦截器

通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。

功能说明
目的是避免在没登陆的情况下,直接通过路径名访问项目,其他人只要知道你项目路径也可以访问,这不是你想要的局面。

Controller层

package com.wq.myweb.controller;


import com.wq.myweb.dao.LoginMapper;
import com.wq.myweb.pojo.Login;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LoginMapper loginMapper;

    @GetMapping("/loginck")
    public String login(Model model) {
        model.addAttribute("user", new Login());
        return "manage/login";
    }
    @PostMapping("/loginck")
    public String logins(String username,String userpassword,HttpSession session, Model model)  {
        String MD5password = encrypt(userpassword);
        Login userck = loginMapper.loginCheck(username,MD5password);
        if (userck != null) {
            /*分别传id,传密码*/
            session.setAttribute("userck",userck);
            session.setAttribute("userpassword",userpassword);
            model.addAttribute("login", userck);
            return "manage/manage";
        } else {
            model.addAttribute("errLogin","账号或密码错误");
            return "redirect:loginck";
        }
    }
    @GetMapping("/ERRO")
    public String ErroJUMP(){
        return "ErroPage";
    }

    /*编译*/
    private String encrypt(String password) {
        String passwordMd5 = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(password.getBytes("utf-8"));
            passwordMd5 = toHex(bytes);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return passwordMd5;
    }

    /*字符串编成16进制数字使用于所有字符*/
    private static String toHex(byte[] bytes) {
        /*16进制数字字符集*/
        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        /*改变这个字符串对象的字符序列。*/
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i=0; i<bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
}
控制台
您输入的字符串是66
加密后的文件是3295C76ACBF4CAAED33C36B1B5FC2CB1

return true 放行
如果从存放用户名密码的数据库找到账号和密码那就跳转到正确的页面

import com.wq.myweb.pojo.Login;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //执行方法前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Login user = (Login)request.getSession().getAttribute("userck");
        if (user==null){
            System.out.println("不放行");
            response.sendRedirect("/login/ERRO");
            return false;
        }else {
            System.out.println("放行");
            return true;
        }
    }
    Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }

前台内容不做拦截,后台只有登陆了才能跳到管理界面

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Autowired
    private LoginHandlerInterceptor loginHandlerInterceptor;

    //这个方法是用来配置静态资源的,比如html,js,css,等等
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**");
    }
    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加拦截的请求,并排除几个不拦截的请求        registry.addInterceptor(loginHandlerInterceptor).addPathPatterns("/manageArticles/**","/manageMedia/**","/manageNotice","/manageVisit/**","/manageComments/**","/password/**")
        .excludePathPatterns("/article/**","/login/**");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值