SpringBoot10:首页实现和登录功能实现及拦截器

首页实现

1、在templates目录下新建首页index.html

注意:所有页面的静态资源都需要使用thymeleaf接管

所有的url路径:@{}

<!DOCTYPE html>
<html lang="en-US" 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="@{/css/bootstrap.min.css}" rel="stylesheet">
      <!-- Custom styles for this template -->
      <link th:href="@{/css/signin.css}" rel="stylesheet">
   </head>

   <body class="text-center">
      <form class="form-signin" th:action="@{/user/login}">
         <img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
         <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}"></h1>
         <!-- 如果msg的值为空,则不显示消息-->
         <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
         <input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
         <input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
         <div class="checkbox mb-3">
            <label>
          <input type="checkbox" th:text="#{login.remember}">
        </label>
         </div>
         <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}"></button>
         <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
         <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
         <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
      </form>

   </body>

</html>

2、在启动类的同级目录下新建config目录,在config目录下编写MyMvcConfig类,实现WebMvcConfigurer接口的addViewControllers方法,在类上添加@Configuration注释,

package com.edgar.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

}

3、测试成功!

请求地址http://localhost:8080/http://localhost:8080/index.html都会返回首页。

登录功能

1、首页中的form表单的请求地址 /user/login

45qcyn.png

2、在启动类的同级目录下新建controller目录,在controller目录下编写LoginController类

package com.edgar.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @RequestMapping("/user/login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model,
            HttpSession session) {
        // 具体的业务
        if (StringUtils.hasLength(username) && "123456".equals(password)) {
            return "dashboard"; // 登录成功,跳转至templates目录下的dashboard.html页面
        } else {
            // 告诉用户,你登陆失败了!
            model.addAttribute("msg","用户名或者密码错误!");
            return "index"; 
        }
    }
}

3、测试成功!

如果登录成功会跳转至 dashboard.html 页面,否也会在首页红字提示 用户名或者密码错误!

拦截器

1、在config目录下新建LoginHandlerInterceptor类实现HandlerInterceptor接口

package com.edgar.config;

import org.springframework.web.servlet.HandlerInterceptor;

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

public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 登陆成功之后,应该有用户的 session
        Object loginUser = request.getSession().getAttribute("loginUser");

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

2、通过MVC扩展类,将LoginHandlerInterceptor组件注册到Spring容器中

package com.edgar.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**") // 拦截所有的路径
                .excludePathPatterns("/index.html","/","/user/login","/css/**","/img/**","/js/**"); // 排除对配置路径的拦截 
    }
}

3、测试成功!

除了配置的排除路径以外,如果用户没有登录成功,其它请求路径都会请求转发到首页!

45OmE6.png

posted @ 2021-09-29 23:45  EdgarStudy  阅读(221)  评论(0)    收藏  举报