【spring boot笔记】8.(Web 开发)实现登录及登录拦截器

登录

1.首先使用spring initializer创建一个web工程:

在这里插入图片描述
工程的名字随便填就可以了,然后项目的类型是maven类型,方面管理各种依赖:
在这里插入图片描述
然后勾上一个web模块:
在这里插入图片描述

2.完善一下工程文件

spring boot中的静态资源文件夹为:

  • classpath:/META‐INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/
  • /:当前项目的根路径

其中, 类路径(classpath) 为/src/main下的/java及resources/文件夹,如下图所示:
在这里插入图片描述


现在在sources中创建public、resources、static、templates文件夹来存放我们的资源文件,如下图所示:
在这里插入图片描述
其中templates文件夹中存放我们的html文件thymeleaf设置了文件路径的前后缀,会帮助我们找到这些templates下的html文件。


然后在我们的Application文件的同层目录下添加config和controller文件夹,分别存放我们的配置类和控制类,如下图所示:
在这里插入图片描述

3.我们先随便写点东西跑通一下代码:

(这个步骤和我们的登录页面没有什么关系,只是随便写写测试一下代码跑不跑得通,然后看一下页面)

在这里插入图片描述
如上图所示,在Application文件的同级目录下创建文件夹controller文件夹用于存放控制器,然后在这个文件夹下面新建一个控制器取名为HelloController.java。HelloController.java的代码如下:

package com.learning.learning04_01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String Hello(){
        return "Hello World";
    }

    @ResponseBody
    @RequestMapping("/")
    public String MainPage(){
        return "this is the main page";
    }
}

上面这段代码里面有两个mapping映射器,映射了两个路径"/“和”/hello"。
当我们在浏览器中输入地址:http://localhost:8080/hello,显示为:
在这里插入图片描述
当在浏览器中输入地址:http://localhost:8080/,显示为:
在这里插入图片描述

如果第2步能成功显示页面说明项目的基础搭建是完善的,可以开始写登录页面了。

3.导入依赖和资源文件
  • 3.1 导入jquery、thymeleaf、bootstrap的manven依赖
组件功能
jquery前端渲染
thymeleaf模板引擎
bootstrap前端框架

前端渲染肯定要用到jquery,模板引擎spring boot推荐thymeleaf,同时这里使用bootstrap的前端框架,因此导入这三个依赖。在百度上搜索webjars,然后进入到webjars网站的主页面,并复制jquery和bootstrap的maven依赖:
在这里插入图片描述
在这里插入图片描述
将代码复制到工程的pom.xml文件中,maven会帮助我们自动下载jquery相关的库。
它们三个的依赖如下:
jquery依赖:

<dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1-2</version>
</dependency>

bootstrap的依赖:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.3.1</version>
</dependency>

thymeleaf的依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 3.2 导入其他静态资源
    例如css,js,html等

4.登录页面
  • 4.1 写一个登录的控制器
    控制器的代码如下:
  @PostMapping(value="/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String,Object> map, HttpSession session){
        if(!StringUtils.isEmpty(username)&&password.equals("123456")){
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        }else{
            map.put("msg","用户名密码错误");
            return "login";
        }
    }
  • 代码中包含了3个前后端交流的变量:username、password和map
  • @PostMapping(value="/user/login")表示接收路由路径为/user/login的响应
  • 方法中的参数@RequestParam(“username”)表示前端一定要传递过来一个参数"username",否则就报错
  • Map<String,Object> map的作用是存储一个报错信息的值,当用户名密码不对或者有其他错误时,后端会将map的值传回给前端进行错误信息显示
  • session用于服务器存储用户登录状态
  • 当用户名和密码正确时,不能直接跳到主页(因为会重复提交登录页面的表单信息),需要进行重定向也就是redirect
  • 当有错误时,重新返回到登录页面"login"

登录页面login.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 href="asserts/css/bootstrap.min.css" rel="stylesheet">
		<!-- Custom styles for this template -->
		<link href="asserts/css/signin.css" rel="stylesheet">
	</head>

	<body class="text-center">
		<form class="form-signin" action="dashboard.html"th:action="@{/user/login}" method="post">
			<img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
			<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
			<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
			<label class="sr-only">Username</label>
			<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
			<label class="sr-only">Password</label>
			<input type="password" name="password" class="form-control" placeholder="Password" required="">
			<div class="checkbox mb-3">
				<label>
          <input type="checkbox" value="remember-me"> Remember me
        </label>
			</div>
			<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</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>

  • 首先在登录页面中我们需要thymeleaf,因此要在<html>标签中添加名称空间:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  • 然后在样式中增加thymeleaf的标识(th:href、th:src等)。设置css样式时,默认路径是source路径。例如href="asserts/css/bootstrap.min.css"指的是source文件夹下的asserts下的css文件夹下的bootstrap.min.css文件,而不是当前文件夹下的asserts下的css文件夹下的bootstrap.min.css文件。
  • 由【action=“dashboard.html”】可知,表单数据提交到了dashboard.html文件中
  • 文件中的th:href及th:src等帮助找到文件的css样式及图片索引

  • login.html中有一段代码为:
<p style="color:red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

这段代码的意思是,登录失败后,msg将不为空,会显示msg的值即“用户名密码错误”。但是如果登录成功,则msg的值为空,就不会显示该字段



拦截器

拦截器的功能是:当用户提交错误的用户名和密码时,阻止用户进入主页面;同时当用户尝试不登录就直接通过url地址访问主页面时,将用户拦截下来。
拦截器LoginHandlerInterceptor.java代码如下:

 @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null) {
            request.setAttribute("msg", "没有权限,请先登录");
            // request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        } else {
            return true;
        }
    }
  • 拦截器先从server端获得用户的session信息,如果存在用户的session则允许通行
  • 如果没有用户的session则标注错误信息“没有权限,请先登录”
  • 下面转发的语句可写可不写,因为控制器中已经设置了页面重定向:
request.getRequestDispatcher("/index.html").forward(request, response);
  • 拦截器写完后需要在配置文件中注册一下:
package com.learning.learning04_01.config;

import com.learning.learning04_01.component.LoginHandlerInterceptor;
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.*;

import java.util.Locale;

//@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Bean
    public WebMvcConfigurer WebMvcConfigurer() {
        WebMvcConfigurer adapter = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                WebMvcConfigurer.super.addViewControllers(registry);
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");

            }

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("index.html","/","/user/login");
            }
        };
        return adapter;
    }
}

  • 当浏览器访问的路径为"…/index.html"会跳转到"login.html"的文件下
  • 拦截器会拦截所有localhost:8080下的页面除了"index.html"、"/"、"/user/login"即我们的登录页
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值