springboot登录和拦截器详解

一 、登录及跳转主页总体步骤

1.登录HTML添加动作跳转,用户名和密码以及密码错误提示框

在这里插入代码片`<!DOCTYPE html>
<!--&lt;!&ndash;<html lang="en">&ndash;&gt;    这个是默认的,后面加上对应的模板引擎-->
<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" th:text="#{login.tip}">Please sign in</h1>
	<!--加入p标签,标签的颜色设置为红色,标签的内容由controller中msg获得-->
	<!--使用if方法,同时变量表达式中的内置工具判断msg是否为空-->
	<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" th:placeholder="#{login.username}" autofocus="">
	<label class="sr-only" th:text="#{login.password}">Password</label>
	<input type="password" name = "password" class="form-control" placeholder="Password" th:placeholder="#{login.password}">

	<div class="checkbox mb-3">
		<label>
			<input type="checkbox" value="remember-me"> [[#{login.remember}]]
		</label>
	</div>
	<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
	<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<!--	下面是根据点击请求带上对应的zh_CN字符放到连接中,后面就去链接中截取这个关键字,然后切换视图-->
	<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.配置“WebMvcConfigurerAdapter”函数

package Main.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class mvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/ceshi").setViewName("hello");
        registry.addViewController("/ceshisuccess").setViewName("success");
        //前面是请求,http://localhost:8080/hello  因为没有hello.html 程序会去controller显示返回值
        //       http://localhost:8080/ceshisuccess,controller也没有对应的处理函数,它是直接去html,显示信息

    }
    //上下两种方法都可以直接不用再controller里面写getMapping了,这种方法直接去到templates下的html页面
    @Bean   //将定义的东西放到容器中,这样能被扫描到
    public WebMvcConfigurerAdapter WebMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override   //这个可以用右键generate、Override 然后就找到对应的函数了
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                //这个是去主页的重定向,只是登录页面不需要
                registry.addViewController("/main.html").setViewName("dashboard");
            }
        };
        return adapter;
    }

}

3.对应的controller(处理登录过程中密码校验)

package Main.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {
    //去前端页面获取对应参数值
    @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) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
//            return "dashboard";

            //登陆成功,防止表单重复提交,可以重定向到主页
            return "redirect:/main.html";//我这里直接dashboard.html会出现40错,这样就不会出错
        }else{
            //登陆失败
            //这个msg被传回到前端,前端写了个标签,如果用户密码错误,提示相应信息
            map.put("msg","用户名密码错误");
            return  "login";
        }

    }
}

二、下面是基于原始restful-crud为什么要添加这些修改值的详解(针对登录及跳转主页)

1.登录

1.配置“WebMvcConfigurerAdapter”函数
该函数让用户输入“http://localhost:8080”直接跳转到“login.html”

package Main.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class mvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/ceshi").setViewName("hello");
        registry.addViewController("/ceshisuccess").setViewName("success");
        //前面是请求,http://localhost:8080/hello  因为没有hello.html 程序会去controller显示返回值
        //       http://localhost:8080/ceshisuccess,controller也没有对应的处理函数,它是直接去html,显示信息

    }
    //上下两种方法都可以直接不用再controller里面写getMapping了,这种方法直接去到templates下的html页面
    @Bean   //将定义的东西放到容器中,这样能被扫描到
    public WebMvcConfigurerAdapter WebMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override   //这个可以用右键generate、Override 然后就找到对应的函数了
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                //这个是去主页的重定向,只是登录页面不需要
                registry.addViewController("/main.html").setViewName("dashboard");
            }
        };
        return adapter;
    }
    
}

2.登录后跳转到主页

2.1.在“login.html”添加跳转到主页的动作

原始login.html

<!DOCTYPE html>
<html lang="en">
	<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">

	<!--  action  这里有跳转到主页的动作-->
		<form class="form-signin" action="dashboard.html">
			<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>
			<label class="sr-only">Username</label>
			<input type="text" class="form-control" placeholder="Username" required="" autofocus="">
			<label class="sr-only">Password</label>
			<input type="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>

因为我们要通过登录跳转到主页需要登录密码和账号验证,所以要写个controller对登录跳转主页进行设置

<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">

2.2.对应的controller

package Main.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {
    //去前端页面获取对应参数值
    @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) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
            return "dashboard";
        }else{
            //登陆失败
            //这个msg被传回到前端,前端写了个标签,如果用户密码错误,提示相应信息
            map.put("msg","用户名密码错误");
            return  "login";
        }

    }
}

2.3错误及排查

不幸的是页面出现错误
在这里插入图片描述
40开头的错误一般是客户端的原因导致的,所以回去排查一下
原来是密码和账号名没有设置参数名称,这样在controller中无对应参数,所以会报错
在这里插入图片描述
在这里插入图片描述
添加对应的参数:
在这里插入图片描述
添加参数,还添加了一个报错后提示密码错误的框及动作跳转到对应的controller

<!DOCTYPE html>
<!--&lt;!&ndash;<html lang="en">&ndash;&gt;    这个是默认的,后面加上对应的模板引擎-->
<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" th:text="#{login.tip}">Please sign in</h1>
	<!--加入p标签,标签的颜色设置为红色,标签的内容由controller中msg获得-->
	<!--使用if方法,同时变量表达式中的内置工具判断msg是否为空-->
	<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" th:placeholder="#{login.username}" autofocus="">
	<label class="sr-only" th:text="#{login.password}">Password</label>
	<input type="password" name = "password" class="form-control" placeholder="Password" th:placeholder="#{login.password}">

	<div class="checkbox mb-3">
		<label>
			<input type="checkbox" value="remember-me"> [[#{login.remember}]]
		</label>
	</div>
	<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
	<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<!--	下面是根据点击请求带上对应的zh_CN字符放到连接中,后面就去链接中截取这个关键字,然后切换视图-->
	<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>

重新运行程序
在这里插入图片描述
页面不正常,且刷新会询问是否重新提交表单
在这里插入图片描述
要页面重定向解决

package Main.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {
    //去前端页面获取对应参数值
    @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) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
//            return "dashboard";

            //登陆成功,防止表单重复提交,可以重定向到主页
            return "redirect:/main.html";//我这里直接dashboard.html会出现40错,这样就不会出错
        }else{
            //登陆失败
            //这个msg被传回到前端,前端写了个标签,如果用户密码错误,提示相应信息
            map.put("msg","用户名密码错误");
            return  "login";
        }

    }
}

三、拦截器

拦截器即对用户的请求进行拦截,防止直接跳过登录进入对应内容页。如直接输入 http://localhost:8080/main.html
在这里插入图片描述
直接进入主页,所以要加拦截器

1.新建一个拦截器实现类

在这里插入图片描述

package Main.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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{
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
            //未登陆,返回登录页面
            request.setAttribute("msg","没有登陆,请先登陆");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else {
            //已登陆,放行请求
            return true;
        }
    }
    //下面三个方法是实现接口HandlerInterceptor必须要的方法
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

2.配置MVC

在这里插入图片描述

package Main.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class mvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/ceshi").setViewName("hello");
        registry.addViewController("/ceshisuccess").setViewName("success");
        //前面是请求,http://localhost:8080/hello  因为没有hello.html 程序会去controller显示返回值
        //       http://localhost:8080/ceshisuccess,controller也没有对应的处理函数,它是直接去html,显示信息

    }
    //上下两种方法都可以直接不用再controller里面写getMapping了,这种方法直接去到templates下的html页面
    @Bean   //将定义的东西放到容器中,这样能被扫描到
    public WebMvcConfigurerAdapter WebMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override   //这个可以用右键generate、Override 然后就找到对应的函数了
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                //这个是去主页的重定向,只是登录页面不需要
                registry.addViewController("/main.html").setViewName("dashboard");
            }

            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                //下面的意思是拦截网页下/*全部拦截,但除了"/index.html","/","/user/login"
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/","/user/login");
            }
        };

        return adapter;
    }

}

直接登录主页就会被拦截,让先登录
在这里插入图片描述

小技巧-开发模板引擎后要实时生效

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值