前言

本章通过二种方式来实现登录,第一种:不连接数据库,用模拟登录的方式实现登录,并实现登录拦截。第二种:连接MySQL的方式实现登录与拦截。

1、 不连接数据库,进行一个模拟登录

判断是否符合登录条件是:用户名不为空和密码为String类型的123456

1、首先创建一个配置类MyMvcConfig ,写一个访问html页面的组件

@Configuration
public class MyMvcConfig {
    //配置视图组件
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
                registry.addViewController("/home.html").setViewName("home");
            }
        };
        return adapter;
    }
}

2、登录的具体方法

@Controller
public class LoginController {
    //登录的具体方法
    @RequestMapping("/Users/select")
    public String userLogin(@RequestParam("userName") String userName,
                            @RequestParam("userPass") String userPass,
                            Map map, HttpSession session){
        if (!StringUtils.isEmpty(userName) && "123456".equals(userPass)){
            session.setAttribute("loginUser",userName);
            //登录成功,为了防止表单重复提交,可以重定向到指定页面
            return "redirect:/home.html";
        }else{
            //返回错误的提示信息
            map.put("error","用户名或密码错误");
            return "login";
        }
    }
}

3、创建login的html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<form action="/Users/select" method="post">
    <div id="login">
        账户:<input type="text" name="userName"/>
        <br/>
        密码:<input type="text" name="userPass"/>
        <br/>
        <input type="submit" value="登录"/>
        <!--    错误信息展示    -->
        <div th:text="${error}"></div>
    </div>
</form>
</body>
</html>

4、创建一个拦截器的组件继承HandlerInterceptor重写里面的方法,如果不登录,不能访问别的页面

/**
 * 登录检查
 */
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("error","没有权限请先登录");
            request.getRequestDispatcher("/login.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 {

    }
}

5、把这个组件放入MyMvcConfig配置类中,让他生效即可。

@Configuration
public class MyMvcConfig {
    //配置视图组件
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
                registry.addViewController("/home.html").setViewName("home");
            }
            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                /**
                 * addPathPatterns:拦截哪些请求
                 * excludePathPatterns:不拦截哪些请求
                 */
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").
                        excludePathPatterns("/login.html","/","/Users/select");
            }
        };
        return adapter;
    }
}

6、创建一个登录成功的页面,并显示登录的用户信息

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
欢迎<a th:text="${session.loginUser}"></a>登录成功
</body>
</html>

2、 通过MyBatis连接MySQL数据库进行登录和校验拦截

-- 创建数据库
CREATE DATABASE IF NOT EXISTS zhao DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
-- 创建一个测试用的数据表
create table test_user(
  userId int auto_increment primary key,
  userName varchar(200),
  userPass varchar(200)
)

1、实体类(entity)

public class TestUser{
    private Integer userId;
    private String userName;
    private String userPass;
    //省略Getter和Setter方法
    }

2、接口(mapper)

@Mapper
public interface TestUserMapper{
    TestUser findUserLogin(@Param("userName") String userName, @Param("userPass") String userPass);
}

3、myBatis配置文件(xml)需要注意的是xml的位置,在resources下,但要与java文件夹下的接口的包名一致

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atgugui.springbootweb.mapper.TestUserMapper">
    <select id="findUserLogin" resultType="com.atgugui.springbootweb.entity.TestUser">
        select userName,userPass from test_user where userName=#{userName} and userPass=#{userPass}
    </select>
</mapper>

4、 业务层(service)

public interface TestUserService {
    TestUser findUserLogin(@Param("userName") String userName, @Param("userPass") String userPass);
}

5、 业务实现层(impl)

@Service
public class TestUserServiceImpl implements TestUserService {

    @Resource
    TestUserMapper testUserMapper;

    @Override
    public TestUser findUserLogin(String userName, String userPass) {
        return testUserMapper.findUserLogin(userName, userPass);
    }
}

6、 逻辑控制层(controller)

@Controller
public class LoginController {

    @Resource
    TestUserService testUserService;

    @RequestMapping("/Users/login")
    public String userLogin(@RequestParam("userName") String userName,
                            @RequestParam("userPass") String userPass,
                            Map map, HttpSession session){
//        if (!StringUtils.isEmpty(userName) && "123456".equals(userPass)){
//            session.setAttribute("loginUser",userName);
//            //登录成功,为了防止表单重复提交,可以重定向到指定页面
//            return "redirect:/home.html";
//        }else{
//            map.put("error","用户名或密码错误");
//            return "login";
//        }
        TestUser user = testUserService.findUserLogin(userName, userPass);
        if (user != null){
            session.setAttribute("loginUser",userName);
            //登录成功,为了防止表单重复提交,可以重定向到指定页面
            return "redirect:/home.html";
        }else {
            map.put("error","用户名或密码错误");
            return "login";
        }
    }
}

7、 html页面和拦截器与之前的没有连接数据库的一样,不需要做任何改动

8、项目结构如下

springboot 添加mybatis自定义拦截器 springboot mybatis 拦截器_mybatis

以上就是用户登录的一个简单实例,项目源码https://pan.baidu.com/s/1UxnLp4iDRi02FeALSfhBzg提取码:q795