SpringBoot(三):最简版登录拦截案例

SpringBoot实现登录拦截案例

准备jar包

在springboot中想要展示页面,必须导入thymeleaf依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

根据目录建包

czx.xupt.config
czx.xupt.dao
czx.xupt.interceptor
czx.xupt.pojo

实体类 czx.xupt.pojo

Department

package czx.xupt.pojo;

public class Department {

    private Integer id;
    private String departmentName;

    public Department() {
    }
    
    public Department(int i, String string) {
        this.id = i;
        this.departmentName = string;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    @Override
    public String toString() {
        return "Department [id=" + id + ", departmentName=" + departmentName + "]";
    }
    
}

Employee

package czx.xupt.pojo;

import java.util.Date;

public class Employee {

    private Integer id;
    private String lastName;

    private String email;
    //1 male, 0 female
    private Integer gender;
    private Department department;
    private Date birth;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Employee(Integer id, String lastName, String email, Integer gender,
                    Department department) {
        super();
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.department = department;
        this.birth = new Date();
    }

    public Employee() {
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", department=" + department +
                ", birth=" + birth +
                '}';
    }
    
}

相应的接口 czx.xupt.dao

DepartmentDao

package czx.xupt.dao;

import czx.xupt.pojo.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//模拟数据库
@Repository
public class DepartmentDao {

    private static Map<Integer, Department> departments = null;

    //初始数据
    static{
        departments = new HashMap<Integer, Department>();
        
        departments.put(101, new Department(101, "D-AA"));
        departments.put(102, new Department(102, "D-BB"));
        departments.put(103, new Department(103, "D-CC"));
        departments.put(104, new Department(104, "D-DD"));
        departments.put(105, new Department(105, "D-EE"));
    }

    //获取获得全部部门信息
    public Collection<Department> getDepartments(){
        return departments.values();
    }

    //通过id获取员工信息
    public Department getDepartment(Integer id){
        return departments.get(id);
    }
    
}

EmployeeDao

package czx.xupt.dao;

import czx.xupt.pojo.Department;
import czx.xupt.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//模拟数据库
@Repository
public class EmployeeDao {

    private static Map<Integer, Employee> employees = null;
    
    @Autowired
    private DepartmentDao departmentDao;
    
    static{
        employees = new HashMap<Integer, Employee>();

        employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
    }
    
    private static Integer initId = 1006;

    //新增员工实现id自增
    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }
        
        employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
        employees.put(employee.getId(), employee);
    }

    //获得全部的员工
    public Collection<Employee> getAll(){
        return employees.values();
    }

    //通过id获取员工
    public Employee get(Integer id){
        return employees.get(id);
    }

    //通过id删除员工
    public void delete(Integer id){
        employees.remove(id);
    }
}

拦截器 czx.xupt.interceptor

package czx.xupt.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * #Author:槐序二四
 * #Time:2020/3/3 19:13
 * #Motto:人间荒唐市侩 不如山中作怪🌙.
 */

public class LoginHandleerIntercept implements HandlerInterceptor {

    //判断是否拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginUser = request.getSession().getAttribute("loginUser");

        if (loginUser==null){
            request.setAttribute("msg","没有权限,请先登录");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else {
            return true;
        }
    }
}

配置类 czx.xupt.config

package czx.xupt.config;

import czx.xupt.interceptor.LoginHandleerIntercept;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * #Author:槐序二四
 * #Time:2020/3/3 18:43
 * #Motto:人间荒唐市侩 不如山中作怪🌙.
 */

//了解即可 一般不这么写
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    //通过配置类来设置视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }


    //添加过滤器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandleerIntercept())
                .addPathPatterns("/**")
                .excludePathPatterns("/index.html","/","/user/login")
                .excludePathPatterns("/asserts/**");
    }
}

页面

首页 index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="description" content="">
      <meta name="author" content="">
      <title>Signin Template for Bootstrap</title>
      <!-- Bootstrap core CSS -->
      <link th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
      <!-- Custom styles for this template -->
      <link th:href="@{/asserts/css/signin.css}" rel="stylesheet">
   </head>

   <body class="text-center">
      <form class="form-signin" th:action="@{/user/login}">
         <img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
         <h1 class="h3 mb-3 font-weight-normal">登录</h1>

         <!--判断是否有错误信息-->
         <p th:if="${not #strings.isEmpty(msg)}" th:text="${msg}" style="color: red"></p>

         <label class="sr-only">Username</label>
         <input type="text" class="form-control" name="username" placeholder="Username" required=""
               autofocus="">
         <label class="sr-only">Password</label>
         <input type="password" class="form-control" name="password" placeholder="Password" required="">
         <div class="checkbox mb-3">
            <label>
                 <input type="checkbox" value="remember-me"> 记住我
              </label>
         </div>
         <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
         <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
         <a class="btn btn-sm">中文</a>
         <a class="btn btn-sm">English</a>
      </form>

   </body>

</html>

dashboard.html
list.html
404页面
可以暂时不写,但是一定要创建出来

结果

首页:
在这里插入图片描述

登陆后:
在这里插入图片描述

目录结构

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值