springboot基础--实现默认登录页面

1、搭建项目

依赖中 多加入thymeleaf依赖

xml 复制代码
<dependencies>
        <!--thymeleaf的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--web工程的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--单元测试的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

application.properties

properties 复制代码
#关闭thymeleaf的缓存,避免开发过程中修改页面不生效的情况,在部署的时候可以取消
spring.thymeleaf.cache=false

2、导入静态资源

src/main/resources/templates/login.html

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆页面</title>
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
    <!-- popper.min.js 用于弹窗、提示、下拉菜单 -->
    <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <h2>登录</h2>
        <form method="post" action="#" th:action="@{/user/login}">
            <div class="form-group has-feedback">
                <label for="用户名">用户名:</label>
                <input th:value="${username}" type="text" name="username"  class="form-control" id="username" placeholder="请输入用户名">
            </div>
            <div class="form-group has-feedback">
                <label for="pwd">密码:</label>
                <input type="password" name="password" class="form-control" id="pwd" placeholder="请输入密码">
                <span th:text="${login_error}" class="glyphicon glyphicon-envelope form-control-feedback"></span>
            </div>
            <div class="form-check">
                <label class="form-check-label">
                    <input class="form-check-input" type="checkbox"> 记住我
                </label>
            </div>
            <button type="submit" class="btn btn-primary">登录</button>
            <button type="button" class="btn btn-primary">注册</button>
        </form>
    </div>
</body>
</html>

src/main/resources/templates/list.html

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <title>登陆页面</title>
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
    <!-- popper.min.js 用于弹窗、提示、下拉菜单 -->
    <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <script>
        $(function(){
            $("button:contains('删除')").click(function(){
                $.post("/user/delete",{"id":this.id});
                $(this).parent().parent().remove();
            });
            $("button:contains('修改')").click(function(){
                //弹出修改窗口
                $('#myModal').modal();
                //把User对象转成json对象
                var jsonObj = JSON.parse($(this).attr("id"));
                //为修改页面进行赋值
                $('#txt_id').val(jsonObj['id']);
                $('#txt_username').val(jsonObj['username']);
                $('#txt_password').val(jsonObj['password']);
                $('#txt_name').val(jsonObj['name']);
                $('#txt_userSex').val(jsonObj['userSex']);
            });
        })
        //添加的方法
        function add() {
            //弹出新建窗口
            $('#myModal1').modal();
        }
    </script>
</head>
<body>
<div class="container">
    <table class="table table-dark table-hover">
        <thead>
            <tr>
                <th>id</th>
                <th>用户名</th>
                <th>密码</th>
                <th>真实姓名</th>
                <th>性别</th>
                <th>删除</th>
                <th>修改</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="users:${list}">
                <td th:text="${users.id}"></td>
                <td th:text="${users.username}"></td>
                <td th:text="${users.password}"></td>
                <td th:text="${users.name}"></td>
                <td th:text="${users.userSex}"></td>
                <th><button th:id="${users.id}" onclick="return confirm('你确定要删除这条数据吗?')">删除</button></th>
                <th><button th:id="${users}">修改</button></th>
            </tr>
        </tbody>
    </table>
    <button onclick="add()">添加</button>
    <!--添加页面-->
    <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form method="post" action="#" th:action="@{/add.do}">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel1">添加</h4>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="txt_username">用户名</label>
                            <input type="text" name="username" class="form-control" placeholder="用户名">
                        </div>
                        <div class="form-group">
                            <label for="txt_password">密码</label>
                            <input type="password" name="password" class="form-control" placeholder="密码">
                        </div>
                        <div class="form-group">
                            <label for="txt_name">真实姓名</label>
                            <input type="text" name="name" class="form-control" placeholder="真实姓名">
                        </div>
                        <div class="form-group">
                            <label for="txt_userSex">性别</label>
                            <input type="text" name="userSex" class="form-control" placeholder="性别">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                        <input type="submit" value="保存" id="btn_submit1" class="btn btn-primary" /><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!--修改页面-->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form method="post" action="#" th:action="@{/update.do}">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">修改</h4>
                    </div>
                    <div class="modal-body">
                        <input type="text" name="id" id="txt_id" hidden="true">
                        <div class="form-group">
                            <label for="txt_username">用户名</label>
                            <input type="text" name="username" class="form-control" id="txt_username" placeholder="用户名">
                        </div>
                        <div class="form-group">
                            <label for="txt_password">密码</label>
                            <input type="password" name="password" class="form-control" id="txt_password" placeholder="密码">
                        </div>
                        <div class="form-group">
                            <label for="txt_name">真实姓名</label>
                            <input type="text" name="name" class="form-control" id="txt_name" placeholder="真实姓名">
                        </div>
                        <div class="form-group">
                            <label for="txt_userSex">性别</label>
                            <input type="text" name="userSex" class="form-control" id="txt_userSex" placeholder="性别">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                        <input type="submit" value="保存" id="btn_submit" class="btn btn-primary" /><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>

127.0.0.1:8080/login.html 进行页面访问,但是无法访问,因为templates下的文件都是被保护的

只能通过controller的方式访问

通过control访问

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
 
 		@RequestMapping("/test")
	  public String test(){
      	 return "login";
	 }

}

http://127.0.0.1:8080/test 访问测试成功

3、 自定义mvc配置方式默认主页

src/main/java/com/franklin/springbootwebdemo/config/WebMvcConfig.java

通过修改WebMvcConfigure的默认设置来指定页面的默认访问方式

1、构建一个配置类,实现WebMvcConfigurer接口, 重写addViewControllers方法;

2、添加自定义页面的默认主页映射: addViewController().setViewName()

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //转发
        registry.addViewController("/").setViewName("login.html");
//        registry.addViewController("/main.html").setViewName("/list.do");
        //重定向
//        registry.addRedirectViewController("/main.html","list.do");
    }


}

测试 访问登录http://127.0.0.1:8080/

注意此时http://127.0.0.1:8080/test 还可以访问成功

4、升级controller

java 复制代码
package com.franklin.springbootwebdemo.controller;

import com.franklin.springbootwebdemo.entity.Users;
import com.franklin.springbootwebdemo.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UsersRepository usersRepository;
    @RequestMapping("/user/login")
    public String login(ModelMap map, Users users, HttpSession session){
        map.addAttribute("username",users.getUsername());
        //进行用户名密码的校验
        if(!StringUtils.isEmpty(users.getUsername())&&!StringUtils.isEmpty(users.getPassword())&&
                "zhangsan".equals(users.getUsername())&&"123456".equals(users.getPassword())){
            //登录成功,把当前user对象注入到session中,进入拦截器里配置
            session.setAttribute("userInfo",users);
            return "list";
        }else{
            map.addAttribute("login_error","用户名密码错误");
            return "login";
        }

    }

}

5、 repository类

src/main/java/com/hckj/managersystemdemo/repository/UsersRepository.java

java 复制代码
package com.franklin.springbootwebdemo.repository;

import com.franklin.springbootwebdemo.entity.Users;

import java.util.List;

public interface UsersRepository {
    List<Users> findAll();
    int deleteUserById(int id);
}

src/main/java/com/hckj/managersystemdemo/repository/UserRepositoryImp.java

java 复制代码
package com.franklin.springbootwebdemo.repository;


import com.franklin.springbootwebdemo.entity.Users;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;


@Repository
public class UserRepositoryImp implements UsersRepository {
    static List<Users> users = new ArrayList<>();
    static{
        Collections.addAll(users,new Users(1001,"zhangsan","123456","张三","男"),
                new Users(1002,"lisi","123456","李四","女"),
                new Users(1003,"wangwu","123456","王五","男"),
                new Users(1004,"zhaoliu","123456","赵柳","女"),
                new Users(1005,"wangba","123456","网吧","男"));
    }
    @Override
    public List<Users> findAll() {
        return users;
    }

    @Override
    public int deleteUserById(int id) {
        int num = 0;
        Iterator<Users> iterator = users.iterator();
        while(iterator.hasNext()){
            Users users = iterator.next();
            if (users.getId()==id){
                iterator.remove();
                num = 1;
            }
        }
        return num;
    }
}

登录http://127.0.0.1:8080/ 输入账号:admin 密码12345

登录http://127.0.0.1:8080/ 输入账号:zhangsan 密码123456

6、第二次升级controller

java 复制代码
@Controller
public class LoginController {

    @Autowired
    private UsersRepository usersRepository;
    @RequestMapping("/user/login")
    public String login(ModelMap map, Users users, HttpSession session){
        map.addAttribute("username",users.getUsername());
        //进行用户名密码的校验
        if(!StringUtils.isEmpty(users.getUsername())&&!StringUtils.isEmpty(users.getPassword())&&
                "zhangsan".equals(users.getUsername())&&"123456".equals(users.getPassword())){
            //登录成功,把当前user对象注入到session中,进入拦截器里配置
            session.setAttribute("userInfo",users);
            return "redirect:/user/list";
        }else{
            map.addAttribute("login_error","用户名密码错误");
            return "login.html";
        }

    }
    @RequestMapping("/user/list")
    public String show(ModelMap map){
        List<Users> list = usersRepository.findAll();
        map.addAttribute("list",list);
        return "list.html";
    }

}

登录http://127.0.0.1:8080/ 输入账号:zhangsan 密码123456

7、数据展示和删除

html 复制代码
    <script>
        $(function(){
            $("button:contains('删除')").click(function(){
                $.post("/user/delete",{"id":this.id});
                $(this).parent().parent().remove();
            });
            $("button:contains('修改')").click(function(){
                //弹出修改窗口
                $('#myModal').modal();
                //把User对象转成json对象
                var jsonObj = JSON.parse($(this).attr("id"));
                //为修改页面进行赋值
                $('#txt_id').val(jsonObj['id']);
                $('#txt_username').val(jsonObj['username']);
                $('#txt_password').val(jsonObj['password']);
                $('#txt_name').val(jsonObj['name']);
                $('#txt_userSex').val(jsonObj['userSex']);
            });
        })
        //添加的方法
        function add() {
            //弹出新建窗口
            $('#myModal1').modal();
        }
    </script>

8、第三次 升级controller

src/main/java/com/hckj/managersystemdemo/controller/LoginController.java

加入

java 复制代码
    @RequestMapping("/user/list")
    public String show(ModelMap map){
        List<Users> list = usersRepository.findAll();
        map.addAttribute("list",list);
        return "list.html";
    }  
		
		@RequestMapping("/user/delete")
    public String delete(int id){
        usersRepository.deleteUserById(id);
        return "list";
    }

9、拦截器

src/main/java/com/hckj/managersystemdemo/intercept/LoginHandlerIntercept.java

java 复制代码
package com.franklin.springbootwebdemo.intercept;




import com.franklin.springbootwebdemo.entity.Users;
import org.springframework.web.servlet.HandlerInterceptor;

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


public class LoginHandlerIntercept implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Users users = (Users) request.getSession().getAttribute("userInfo");
        if (users!=null){
            return true;
        }else{
            request.setAttribute("login_error","请先登录");
            request.getRequestDispatcher("/").forward(request,response);
            return false;
        }
    }
}

src/main/java/com/franklin/springbootwebdemo/config/WebMvcConfig.java

加入

java 复制代码
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerIntercept()).addPathPatterns("/**").excludePathPatterns("/","/eitilogin.html","/user/login","/css/**","js/**","img/**");
    }

测试

访问http://127.0.0.1:8080/user/list 都是跳转到登录界面,测试通过

相关推荐
码上一元2 小时前
SpringBoot自动装配原理解析
java·spring boot·后端
计算机-秋大田2 小时前
基于微信小程序的养老院管理系统的设计与实现,LW+源码+讲解
java·spring boot·微信小程序·小程序·vue
魔道不误砍柴功4 小时前
简单叙述 Spring Boot 启动过程
java·数据库·spring boot
失落的香蕉4 小时前
C语言串讲-2之指针和结构体
java·c语言·开发语言
枫叶_v4 小时前
【SpringBoot】22 Txt、Csv文件的读取和写入
java·spring boot·后端
wclass-zhengge4 小时前
SpringCloud篇(配置中心 - Nacos)
java·spring·spring cloud
路在脚下@4 小时前
Springboot 的Servlet Web 应用、响应式 Web 应用(Reactive)以及非 Web 应用(None)的特点和适用场景
java·spring boot·servlet
黑马师兄4 小时前
SpringBoot
java·spring
数据小小爬虫4 小时前
如何用Java爬虫“偷窥”淘宝商品类目API的返回值
java·爬虫·php
暮春二十四4 小时前
关于用postman调用接口成功但是使用Java代码调用却失败的问题
java·测试工具·postman