SpringBoot博客系统之后台登陆和拦截器配置

登陆的实现逻辑很简单,只需要根据传入的用户名和密码做出相应的判断并和数据库中数据匹配即可

基本实现

1. controller层,先对传入的用户名和密码进行非空判断再调用Service层进行数据库匹配,如果匹配成功则把用户信息存到session域中,并且重定向到admin/index请求,返回index页
主要,因为这里涉及到了表单的提交所以再跳转页的时候一定要使用重定向请求转发和直接返回index页面都不行,因为浏览器地址没变,在刷新的时候会出现反复提交的情况
请求转发和重定向

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }
@GetMapping({ "/index", "/index.html"})
    public String index(HttpServletRequest request) {
        return "admin/index";
    }

    @PostMapping(value = "/login")
    public String login(String userName,
                        String password,
                        HttpSession session) {
        System.out.println(userName);
        System.out.println(password);
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            session.setAttribute("errorMsg", "用户名或密码不能为空");
            return "admin/login";
        }
        AdminUser adminUser = adminService.login(userName, password);
        if (adminUser != null) {
            session.setAttribute("loginUser", adminUser.getNickName());
            session.setAttribute("loginUserId", adminUser.getAdminUserId());
            //session过期时间设置为 即四小时
            session.setMaxInactiveInterval(60 * 60 * 4);
            return "redirect:/admin/index";
        } else {
            System.out.println("登陆失败");
            session.setAttribute("errorMsg", "登陆失败");
            return "admin/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginUserId");
        request.getSession().removeAttribute("loginUser");
        request.getSession().removeAttribute("errorMsg");
        return "admin/login";
    }
}

2. service层
因为存入数据库中的密码要经过MD5加密,所以在校验的时候要先对传进来的密码进行MD5转换,再去数据库比对

@Override
    public AdminUser login(String userName, String password) {
        String passwordMd5 = MD5Utils.code(password);
        return adminUserMapper.getUser(userName, passwordMd5);
    }

其中MD5Utils

public class MD5Utils {
    public static String code(String str){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[]byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }
}

3. dao层

AdminUser getUser(@Param("userName") String userName, @Param("password") String password);
<select id="getUser" resultType="com.javaer.myblog.entity.AdminUser">
        select * from admin_user where login_user_name = #{userName,jdbcType=VARCHAR} AND login_password=#{password,jdbcType=VARCHAR} 
</select>

拦截器配置

配置拦截器是因为,我们所有后台的页面都在/admin请求下,我们希望只有登陆才能访问,但是目前,知道别人知道我们的相应请求地址就能进行访问,所有我们需要拦截下来/admin下的请求经过是否登陆的判断才放行
这里的是否登陆的判断是通过判断session域中是有相应的用户信息来实现的,再登陆的时候我们把用户信息存储在了我们的session域中,所有有相应信息的用户才是登陆了的用户
拦截器

@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin") && null == request.getSession().getAttribute("loginUser")) {
            System.out.println("wrong");
            request.getSession().setAttribute("errorMsg", "请重新登陆");
            response.sendRedirect("/admin");
            return false;
        } else {
            request.getSession().removeAttribute("errorMsg");
            return true;
        }
    }

}

配置拦截器

package com.javaer.myblog.config;

import com.javaer.myblog.interceptor.AdminLoginInterceptor;
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.WebMvcConfigurer;

@Configuration
public class MyBlogWebMvcConfigurer implements WebMvcConfigurer {
    @Autowired
    private AdminLoginInterceptor adminLoginInterceptor;

    public void addInterceptors(InterceptorRegistry registry) {
        // 添加一个拦截器,拦截以/admin为前缀的url路径
        registry.addInterceptor(adminLoginInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")//放行/admin
                .excludePathPatterns("/admin/login")//放行/admin/login
                .excludePathPatterns("/admin/dist/**")
                .excludePathPatterns("/admin/plugins/**");
    }

}
发布了76 篇原创文章 · 获赞 0 · 访问量 2002

猜你喜欢

转载自blog.csdn.net/weixin_43907800/article/details/104181200
今日推荐