接着上个章节来,上章节搭建好框架,并且测试也在页面取到数据。接下来实现web端,实现前后端交互,在前台进行注册登录以及后端***配置。实现简单的未登录拦截跳转到登录页面

上个章节传送门:使用spring boot完成增删改查--(一)查询

首先要实现web端需要在pom里引入jar包,前端用thymeleaf,所以在pom里添加以下内容

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

然后application-dev.yml里配置一下thymeleaf,如下

server:
  port: 8888

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&userSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    mode: html5
    servlet:
      content-type: text/html
mybatis:
  mapper-locations: classpath:mapping/*Mapping.xml
  type-aliases-package: com.example.entity

#showSql
logging:
  level:
    com:
      example:
        mapper: debug

下面写页面吧,在templates里创建需要的页面index.html、register.html、welcome.html。由于目标是实现功能,所以界面很简洁,样式统统省掉了,回归原始

register.html(注册页面)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>register</title>
</head>
<body>

<form action="/user/register" method="post">
    请输入用户名--:<input type="text" name="userName" id="userName" /><br>
    请你输入密码--:<input type="password" name="passWord" id="passWord" /><br>
    <input type="submit" value="Register">
</form>

</body>
</html>

index.html(登录页面)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/user/loginUser" method="post">
    请输入用户名--:<input type="text" name="userName" id="userName" /><br>
    请你输入密码--:<input type="password" name="passWord" id="passWord" /><br>
    <input type="submit" value="Login">
    <a href="/user/toRegister">--注册--</a>
</form>

</body>
</html>

welcome.html(退出登录页面,用于测试***)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

注册或登录后才能看到的界面
<a href="/user/outUser">退出登录</a>
</body>
</html>

页面简洁(丑)到没朋友,下面后台实现逻辑,一套流程直接走起,不多解释了,直接放代码

controller下新建一个LoginController.java。我把注册登录退出登录方法全贴出来了

package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: LYP_PC
 * Date: 2020/2/13
 * Time: 18:09
 * Description: No Description
 */
@Controller
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserService userService;

    // 跳转登录首页(登录页)
    @RequestMapping("/toIndex")
    public String show(){
        return "index";
    }

    //登录操作
    @ResponseBody
    @RequestMapping("/loginUser")
    public String login(User user, HttpServletRequest request){
        String userName = user.getUserName();
        String passWord = user.getPassWord();
        User u1 = userService.login(userName,passWord);
        if(u1 == null){
            return "用户名或密码错误";
        }else{
            request.getSession().setAttribute("session_user",user); //登录成功后将用户放入session
            return "登录成功";
        }
    }

    //跳转注册页
    @RequestMapping("/toRegister")
    public String toRegister(){
        return "register";
    }

    //注册操作
    @RequestMapping("/register")
    public String register(User user){
        int su = userService.register(user);
        if(su == 0){
            System.out.println("----");
        }
        return "welcome";
    }

    //测试未登录拦截界面
    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome";
    }

    //退出登录
    @RequestMapping("/outUser")
    public void outUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("session_user");
        response.sendRedirect("/user/toIndex");
    }
}

UserService.java

package com.example.service;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * User: LYP_PC
 * Date: 2020/2/8
 * Time: 17:55
 * Description: No Description
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;
    public User Sel(int id){
        return userMapper.Sel(id);
    }

    public User login(String userName, String passWord) {
        return userMapper.login(userName,passWord);
    }

    public int register(User user){
        return userMapper.register(user);
    }

}

UserMapper.java

package com.example.mapper;

import com.example.entity.User;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA.
 * User: LYP_PC
 * Date: 2020/2/8
 * Time: 17:57
 * Description: No Description
 */
@Repository
public interface UserMapper {

    User Sel(int id);

    User login(String userName, String passWord);

    int register(User user);

}

UserMapping.xml

<?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.example.mapper.UserMapper">


    <resultMap id="BaseResultMap" type="com.example.entity.User">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="userName" jdbcType="VARCHAR" property="userName"/>
        <result column="passWord" jdbcType="VARCHAR" property="passWord"/>
        <result column="realName" jdbcType="VARCHAR" property="realName"/>
    </resultMap>

    <select id="Sel" resultType="com.example.entity.User">
        select * from user where id = #{id}
    </select>

    <select id="login" resultType="com.example.entity.User">
        select * from user where userName = #{param1} and passWord = #{param2}
    </select>

    <insert id="register" parameterType="User">
        insert into user (userName,password)values (#{userName},#{passWord})
    </insert>
</mapper>

到这里就实现了登录注册了

其实注册登录也诶逻辑也很简单,就不多赘述了,接下来讲讲实现***功能(敲黑板,本章的重点)

首先在com.example下新建intercetor包,然后新建UserIntercetor.java实现HandlerInterceptor接口并重写方法,更多介绍都写在里面注释了

UserIntercetor.java
 

package com.example.intercetor;

import com.example.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Created with IntelliJ IDEA.
 * User: LYP_PC
 * Date: 2020/2/14
 * Time: 17:17
 * Description: No Description
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    /*
    * 进入cpntroller层之前拦截请求
    * 返回值:表示是否将当前的请求拦截下来 false:拦截请求,请求别终止。 true:请求不被拦截,继续执行
    * Object obj:表示被拦的请求的目标对象(controller中方法)
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        System.out.println("执行到了preHandle方法");
        System.out.println(handler);
        User user = (User) request.getSession().getAttribute("session_user");
        if (user==null){
            response.sendRedirect(request.getContextPath()+"/user/toIndex");//拦截后跳转的方法
            System.out.println("已成功拦截并转发跳转");
            return false;
        }
        System.out.println("合格不需要拦截,放行");
        return true;
    }


    /*
    * 处理请求完成后视图渲染之前的处理操作
    * 通过ModelAndView参数改变显示的试图,或发现试图的方法
    *
    */

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("执行了postHandle方法");
    }

    /*
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        System.out.println("执行到了afterCompletion方法");
    }

}

新建类SessionInterceptor实现WebMvcConfigurer接口来注册***

SessionInterceptor.java(类里的注释说明也很详细)

package com.example.intercetor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Coffee君
 * Date: 2020/2/15
 * Time: 10:36
 * Description: No Description
 */
@Configuration
public class SessionInterceptor implements WebMvcConfigurer {

    /*
    * 自定义***,添加拦截路径和排除拦截路径
    * addPathPatterns();添加需要拦截的路径
    * excludePathPatterns();添加不需要拦截的路径
    */
    //添加***
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        List list = new ArrayList();
        list.add("/user/toIndex");
        list.add("/user/loginUser");
        list.add("/user/toRegister");
        list.add("/user/register");
        registry.addInterceptor(new UserInterceptor()).addPathPatterns("/**").excludePathPatterns(list);
    }

}

这个类中我放行了四个请求,一共写了五个请求,还有一个  "/user/welcome"  请求没有放行,就是用于测试***效果。

下面分别看下登录和未登录的拦截效果:

没有登录访问/user/welcome请求时(http://localhost:8888/user/welcome)

由于在session中没有获取到用户,所以UserIntercetor.java里的preHandle方法拦截了下来,并进行重定向到了/toIndex方法,打开了登录页面

再来看下登陆后直接访问/user/welcome请求时(http://localhost:8888/user/welcome)

可以看到页面可以访问打开welcome.html的,后台获取到session中的用户后也放行了。

本章节的任务至此也完成了。

Coffee君祝大家在学习的路上继续前行,一起努力。