Spring+SpringMVC+MP login case (including interceptor)

technical framework

Backend: Spring, Spring MVC, Mybatis-Plus

Front-end: HTML, CSS, Layui, JS, Jquery

 

Functional Module Technology

1. Each request of the user uses SpringMVC interceptor technology, and users who are not logged in are automatically redirected to the login page

2. Unified request mode, using Restful style to initiate requests to the backend

3. Use druid database connection pool technology to manage database connection resources

4. Use session to store user information for logged-in users. The rule of login interceptor interception is to judge whether there is corresponding user information in the session to intercept

 

database structure

User table (tb_user) 

e233074ca8764fefb532020359b83f49.png

 

Orders table (tb_orders)

58836aeac2ad4be08df14eb4eb09c8c8.png

 

Project file structure

d5fc2b69595d4705a99dce497c480dc5.png

 

Project effect

login page

b1f72aec0f124e138f84bf79b6251557.png

 

Home page (displays the order information of the currently logged in user)

c40182173eb14e679835898bc0c3091f.png

 

 

project core file

Tomcat server configuration file (web.xml)

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- Tomcat容器上下文配置参数-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  <!-- 注册SpringMVC提供的过滤器,解决乱码问题-->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 加载SpringMVC容器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>



  <!-- 注册前端控制器-->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <welcome-file-list>
    <welcome-file>/page/login.html</welcome-file>
  </welcome-file-list>
</web-app>

 

spring.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 包扫描  -->
    <context:component-scan base-package="com"></context:component-scan>
    <import resource="springdao.xml"></import>
</beans>

 

springmvc.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置Controller扫描 -->
    <context:component-scan base-package="com.controller" />

    <!-- 配置注解驱动 -->
    <mvc:annotation-driven />

    <!-- 配置静态资源映射 -->
    <mvc:resources location="/static/css/" mapping="/css/**" />
    <mvc:resources location="/static/js/" mapping="/js/**" />
    <mvc:resources location="/static/layui/" mapping="/layui/**" />
    <mvc:resources location="/static/layer/" mapping="/layer/**" />

    <!-- Servlet默认处理器-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
    <!-- 配置拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <!-- 配置不拦截请求的地址 -->
            <mvc:exclude-mapping path="/page/login.html" />
            <mvc:exclude-mapping path="/css/**" />
            <mvc:exclude-mapping path="/" />
            <mvc:exclude-mapping path="/js/**" />
            <mvc:exclude-mapping path="/layui/**" />
            <mvc:exclude-mapping path="/layer/**" />
            <mvc:exclude-mapping path="/login" />
            <bean class="com.inteceptor.LoginInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

springdao.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 加载数据库配置文件  -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!-- 创建Druid数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${db.driver}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
    </bean>

    <!-- 创建sqlsessionFactory的Bean 工厂 -->
    <!-- 这里使用的是 mybatis-plus 创建的MybatisSqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!--设置mybaits的配置文件  这里有两用设置方法 这里是方法一 使用mybatis.xml 的配置文件设置 -->
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>
    <!--mapper scan-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <property name="basePackage" value="com.mapper"></property>
    </bean>

</beans>

 

mybatis.xml file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="stdout_logging" />
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

</configuration>

 

db.properties file (the database configuration information here needs to be changed to your own, such as password and driver)

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&allowMultiQueries=true
db.username=root
db.password=123456

 

Login Interceptor (LoginInterceptor)

package com.inteceptor;

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

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

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取Session
        Object user = request.getSession().getAttribute("user");
        System.out.println("执行拦截器");
        System.out.println(user);
        //检查用户是否登录
        if (user != null){
            //用户已经登录就直接放行
            return true;
        }else {
            //没有登录,就重定向到登录页
            response.sendRedirect("/page/login.html");
        }
        return false;
    }

    @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 {

    }
}

 

LoginController controller

package com.controller;

import com.model.entity.R;
import com.model.entity.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpServletRequest request){
        User one = userService.findByPwd(user);
        if (one != null){
            request.getSession().setAttribute("user",one);
            return R.ok("登录成功");
        }
        return R.fail("账号或密码错误");
    }

    @GetMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("user");
        response.sendRedirect("/page/login.html");
    }

}

Finally, I will give you the entire project file for free, see the comment area

 

 

 

 

Guess you like

Origin blog.csdn.net/calm_programmer/article/details/128350490