springboot基础--实现默认登录页面
作者:mmseoamin日期:2023-12-25

1、搭建项目

依赖中 多加入thymeleaf依赖


        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

application.properties

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

2、导入静态资源

springboot基础--实现默认登录页面,在这里插入图片描述,第1张

springboot基础--实现默认登录页面,第2张

src/main/resources/templates/login.html




    
    登陆页面
    
    
    
    
    
    
    
    


    

登录

src/main/resources/templates/list.html




    
    Title
    登陆页面
    
    
    
    
    
    
    
    
    


id 用户名 密码 真实姓名 性别 删除 修改

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

只能通过controller的方式访问

springboot基础--实现默认登录页面,在这里插入图片描述,第3张

通过control访问

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 访问测试成功

springboot基础--实现默认登录页面,在这里插入图片描述,第4张

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

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

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

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

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

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/

springboot基础--实现默认登录页面,在这里插入图片描述,第5张

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

4、升级controller

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

package com.franklin.springbootwebdemo.repository;
import com.franklin.springbootwebdemo.entity.Users;
import java.util.List;
public interface UsersRepository {
    List findAll();
    int deleteUserById(int id);
}

src/main/java/com/hckj/managersystemdemo/repository/UserRepositoryImp.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 = 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 findAll() {
        return users;
    }
    @Override
    public int deleteUserById(int id) {
        int num = 0;
        Iterator 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

springboot基础--实现默认登录页面,在这里插入图片描述,第6张

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

springboot基础--实现默认登录页面,在这里插入图片描述,第7张

6、第二次升级controller

@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 list = usersRepository.findAll();
        map.addAttribute("list",list);
        return "list.html";
    }
}

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

springboot基础--实现默认登录页面,外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传,第8张

7、数据展示和删除

    

8、第三次 升级controller

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

加入

    @RequestMapping("/user/list")
    public String show(ModelMap map){
        List 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

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

加入

    @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 都是跳转到登录界面,测试通过

springboot基础--实现默认登录页面,在这里插入图片描述,第9张