美文网首页
SpringBoot2 - 拦截器

SpringBoot2 - 拦截器

作者: 朱穆朗玛 | 来源:发表于2018-06-20 18:01 被阅读0次

构建项目

访问start.spring.io/

  1. 修改pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gala</groupId>
    <artifactId>interceptor</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>interceptor</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  1. 修改application.yml
spring:
 datasource:
  type: com.alibaba.druid.pool.DruidDataSource
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
  username: root
  password: 123456
  #配置监控统计拦截的filters
  filters: stat,wall,log4j
  #最大活跃数
  maxActive: 20
  #初始化数量
  initialSize: 1
  #最大连接等待超时时间
  maxWait: 60000
  #打开PSCache,并指定每个连接PSCache的大小
  poolPreparedStatements: true
  maxPoolPreparedStatementPerConnectionSize: 20
  #通过connectionProperties属性打开mergeSql功能
  connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  minldle: 1
  timeBetweenEvictionRunsMillis: 60000
  minEvictableldleTimeMillis: 300000
  validationQuery: select 1 from dual
  testWhiledle: true
  testOnBorrow: false
  testOnReturn: false
 jpa:
  properties:
   hibernate:
    show_sql: true
    format_sql: true
 mvc:
  view:
   prefix: /WEB-INF/views/
   suffix: .jsp

创建视图文件

  1. 在main目录下创建视图文件夹 webapp >> WEB-INF >> views
  2. 新增index.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
    <head>
        <title>主页</title>
    </head>
    <body>
        欢迎访问SpringBoot主页
    </body>
</html>
  1. 新增登录页面
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
    <head>
        <title>登录页</title>
    </head>
    <body>
        <form action="/user/login" method="get">
            <table>
                <tr>
                    <td>用户名</td>
                    <td><input type="text" name="name" /></td>
                </tr>
                <tr>
                    <td>密码</td>
                    <td><input type="text" name="password" /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="登录" /></td>
                </tr>
            </table>
        </form>
    </body>
</html>

创建用户表

DROP TABLE IF EXISTS `t_user`;

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(50) DEFAULT NULL COMMENT '名字',
  `password` varchar(50) DEFAULT NULL COMMENT '密码',
  `age` int DEFAULT '0' COMMENT '年龄',
  `address` varchar(200) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建实体

package com.gala.interceptor.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "t_user")
public class User {

    private Long id;

    private String name;
    
    private String password;

    private Integer age;

    private String address;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

创建JPA

package com.gala.interceptor.jpa;

import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.gala.interceptor.entity.User;

public interface UserDao extends JpaRepository<User, Long>, JpaSpecificationExecutor<User>, Serializable {

}

创建控制器

  1. LoginController.java
package com.gala.interceptor.controller;

import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gala.interceptor.entity.User;
import com.gala.interceptor.jpa.UserDao;

@RestController
@RequestMapping(value = "/user")
public class LoginController {

    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(User user, HttpServletRequest request) {
        boolean flag = true;
        String result = "登录成功";

        Optional<User> existUser = userDao.findOne(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                query.where(criteriaBuilder.equal(root.get("name"), user.getName()));
                return null;
            }
        });

        if (existUser == null) {
            flag = false;
            result = "用户不存在,登录失败";
        } else if (!existUser.get().getPassword().equals(user.getPassword())) {
            flag = false;
            result = "密码不正确,登录失败";
        }

        if (flag) {
            request.getSession().setAttribute("_session_user", existUser);
        }

        return result;
    }

}
  1. IndexController.java
package com.gala.interceptor.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/user")
public class IndexController {

    @RequestMapping(value = "/preLogin", method = RequestMethod.GET)
    public String preLogin() {
        return "login";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "index";
    }

}

创建拦截器

package com.gala.interceptor;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 登录不拦截
        if (request.getRequestURI().equals("/user/login") || request.getRequestURI().equals("/user/preLogin")) {
            return true;
        }

        // 验证session是否存在
        Object obj = request.getSession().getAttribute("_session_user");
        if (obj == null) {
            response.sendRedirect("/user/preLogin");
            return false;
        }
        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 {
    }
}

SessionInterceptor拦截器添加到SpringBoot的配置中
新建SessionConfiguration.java,配置拦截器


package com.gala.interceptor;

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

@Configuration
public class SessionConfiguration implements WebMvcConfigurer {

    /**
     * 将拦截器配置到SpringBoot中
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SessionInterceptor()).addPathPatterns("/**");
    }
}

启动项目

  1. 访问http://127.0.0.1:8080/user/index

  2. 输入用户名密码 admin/123456,然后登录


  3. 再次访问http://127.0.0.1:8080/user/index

相关文章

网友评论

      本文标题:SpringBoot2 - 拦截器

      本文链接:https://www.haomeiwen.com/subject/twpxyftx.html