SpringBoot登录实现

288 阅读2分钟

建议大家先看整体流程图,明白我要做什么,然后动手跟着一起实践一下哦。

使用index.html作为欢迎页面

SpringBoot项目在启动后,首先会去静态资源resource/static下查找index.html 作为首页文件,记载静态页面的内容。如果在静态资源路径下找不到,则会到resource/templates目录下找index.html 这里使用Thymeleaf模板作为动态页面的首页文件 。

  • 静态页面 resource/static/index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <body>
            <h2>登录</h2>
    </body>
    </html>
    
  • 动态页面 resource/templates/index.html 下文提到的resource/templates/login.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>
    
  • list.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>
    

pom.xml 引入模板依赖

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

使用login.html(或其他页面)作为欢迎页面

  • 静态页面
  1. 通过自定义一个controller来转发

    @Controller
    public class HelloContorller {    
    @RequestMapping("/")    
    public String hello(){    
        return "forward:login.html";   
    }  
    
  2. 自定义一个MVC配置并重写addViewControllers方法进行转发

    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer { 
        @Override    
        public void addViewControllers(ViewControllerRegistry registry){
            registry.addViewController("/").setViewName("login.html");
        }
    }
    
  • 动态页面
  1. 自定义一个controller来转发

    @Controller
    public class HelloContorller {    
    @RequestMapping("/")    
    public String hello(){    
        return "login";   
    }  
    
  2. 自定义一个MVC配置并重写addViewControllers方法进行转发

    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer { 
        @Override    
        public void addViewControllers(ViewControllerRegistry registry){
            registry.addViewController("/").setViewName("login");
        }
    }
    

整体结构图

数据准备

  • 实体

    @Data
    public class User {
        private int id;
        private String username;
        private String password;
        private String name;
        private String userSex;
        
        public User() {
        }
    
        public User(int id, String username, String password, String name, String userSex) {
            this.id = id;
            this.username = username;
            this.password = password;
            this.name = name;
            this.userSex = userSex;
        }
    }
    
  • 数据层

    @Repository
    public class UserRepositoryImpl implements UserRepository {
        static List<User> users = new ArrayList<>();
        static{
            Collections.addAll(users,new User(1001,"zhangsan","123456","张三","男"),
                    new User(1002,"lisi","123456","李四","女"),
                    new User(1003,"wangwu","123456","王五","男"),
                    new User(1004,"zhaoliu","123456","赵柳","女"),
                    new User(1005,"wangba","123456","网吧","男"));
        }
        @Override
        public List<User> findAll() {
            return users;
        }
    
        @Override
        public int deleteById(int id) {
            int num = 0 ;
            Iterator<User> iterator = users.iterator();
            while (iterator.hasNext()){
                User user = iterator.next();
                if(user.getId() == id){
                    iterator.remove();
                    num++;
                }
            }
            return 0;
        }
    }
    

控制层:登录、查询、删除

@Controller
public class LoginController {
    @Autowired
    private UserRepository userRepository;

    //登录
    @RequestMapping(value = "/user/login")
    public String login(ModelMap modelMap,  User user , HttpSession httpSession){
        modelMap.addAttribute("username",user.getUsername());
        if(!StringUtils.isEmpty(user.getUsername())&&!StringUtils.isEmpty(user.getPassword())&&"zhangsan".equals(user.getUsername()) &&"123456".equals(user.getPassword())){
            httpSession.setAttribute("userInfo",user);
            return "redirect:/user/list";
        }else {
            modelMap.addAttribute("login_error","用户名或密码错误");
            return "login" ;
        }

    }
    //查询
    @RequestMapping("/user/list")
    public String show(ModelMap modelMap){
        List<User> users = userRepository.findAll();
        modelMap.addAttribute("list",users);
        return "list";
    }
    //删除
    @RequestMapping("/user/delete")
    public String delete(int id){
        userRepository.deleteById(id);
        return "list";
    }
}

拦截器

  • 拦截器拦截未登录用户

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

  • 注册拦截器

    @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginHandlerIntercept()).addPathPatterns("/**").excludePathPatterns("/","/user/login"); } }

项目结构图