SpringBoot简单实现登录功能

登陆

开发期间模板引擎页面修改以后,要实时生效

1)、禁用模板引擎的缓存

# 禁用缓存
spring.thymeleaf.cache=false 

2)、页面修改完成以后ctrl+f9:重新编译;

登陆错误消息的显示

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

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" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="asserts/css/signin.css" th: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" th:src="@{/asserts/img/bootstrap-solid.svg}" 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 style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
            <label class="sr-only" th:text="#{login.username}">Username</label>
            <input type="text"  name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" 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}" required="">
            <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>
            <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>

4)、Controller层

LoginController:

package com.atguigu.springboot.controller;

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

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

@Controller
public class LoginController {

//    @DeleteMapping
//    @PutMapping
//    @GetMapping

    //@RequestMapping(value = "/user/login",method = RequestMethod.POST)
    @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 "redirect:/main.html";
        }else{
            //登陆失败

            map.put("msg","用户名密码错误");
            return  "login";
        }

    }
}

4)、拦截器进行登陆检查

拦截器

package com.atguigu.springboot.component;

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;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
注册拦截器:
package com.atguigu.springboot.config;

import com.atguigu.springboot.component.LoginHandlerInterceptor;import com.atguigu.springboot.component.MyLocaleResolver;import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;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.EnableWebMvc;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能//@EnableWebMvc   //不要接管SpringMVC@Configurationpublic class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override    public void addViewControllers(ViewControllerRegistry registry) {       // super.addViewControllers(registry);        //浏览器发送 /atguigu 请求来到 success        registry.addViewController("/atguigu").setViewName("success");    }

    //所有的WebMvcConfigurerAdapter组件都会一起起作用    @Bean //将组件注册在容器    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {            @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已经做好了静态资源映射                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")                        .excludePathPatterns("/index.html","/","/user/login");            }        };        return adapter;    }

    @Bean    public LocaleResolver localeResolver(){

        return new MyLocaleResolver();    }

}

原文地址:https://www.cnblogs.com/zqLoveSym/p/10570557.html

时间: 2024-10-28 12:38:08

SpringBoot简单实现登录功能的相关文章

struts2 简单的登录功能

学了一定的jsp基础之后,我们可以试着去尝试去实现一个简单的struts2的动态登录功能,具体代码如下: 一.目录结构 首先,lib中导入struts2所需的核心包, 下载地址:http://struts.apache.org/download.cgi#struts23281 总体目录结构如下: 二.web.xml中 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="ht

Flutter-实现一个简单的登录功能

登录逻辑判断 1.缓存token,使用的是shared_preferences 最新版本(https://pub.flutter-io.cn/packages/shared_preferences) shared_preferences: ^0.5.6 简单封装一层 class MTCacheTool { // 存储token static const String keyToken = 'xxxxxxxxxTK'; // 存储用户名 static const String keyUserNam

2. 简单的登录功能实现

1. 在WebContent目录下创建 login.jsp 1 <%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <head><ti

航空机票预定及销售系统(一)——试水+简单的登录功能

<!DOCTYPE html> <html> <head> <meta charset="gb2312"> <title>用户登录</title> </head> <body> <h3><b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp用户登录<

Flask 【第四篇】使用Flask的扩展实现简单页面登录功能

from flask import Flask,render_template,request,redirect,session app = Flask(__name__,template_folder='templates') app.secret_key = "sdsfdsgdfgdfgfh" @app.before_request def process_request(): if request.path=="/login": return None if

ASP.NET中登录功能的简单逻辑设计

 ASP.NET中登录功能的简单逻辑设计                               概述                               逻辑设计                               1.接收参数                               2.判断参数合法性                               3.访问数据库                               4.保存Session     

【Android】Android 博客园客户端 (七)登录功能

如题,不过只是简单的登录功能,登录成功以后可以进行的操作还没有进行实现. 登录的原理主要是获取Cookies,数据保存在数据库中.使用HttpClient模拟登录的方式已经在另一篇博客中写过,这里就不再赘述. 博客地址:http://www.cnblogs.com/zhangtingkuo/p/3968450.html 登录的流程如图所示: 代码非常简单: SplashActivity: 1 if (Personal.isLogin(this)) { 2 Config.FLAG_LOGIN =

Android 博客园客户端 (七)登录功能

如题,不过只是简单的登录功能,登录成功以后可以进行的操作还没有进行实现. 登录的原理主要是获取Cookies,数据保存在数据库中.使用HttpClient模拟登录的方式已经在另一篇博客中写过,这里就不再赘述. 博客地址:http://www.cnblogs.com/zhangtingkuo/p/3968450.html 登录的流程如图所示: 代码非常简单: SplashActivity: 1 if (Personal.isLogin(this)) { 2 Config.FLAG_LOGIN =

SSM框架实现登录功能 (后台)

SSM框架实现简单的登录功能,需要实现查询数据库中user并比对输入的账号密码 首先需要创建实体类,表中各个字段在实体类中写出来,并写出构造方法,get set方法 Mapper: <mapper namespace="User"> <resultMap type="com.zy.music.pojo.User" id="userResult"> <id property="userId" col