Spring+SpringMVC+MP登录案例(含拦截器)

news2024/9/30 23:35:50

技术框架

后端:Spring、Spring MVC、Mybatis-Plus

前端:HTML、CSS、Layui、JS、Jquery

功能模块技术

1、用户的每一个请求使用了SpringMVC 拦截器技术,没有登录的用户自动重定向到登录页

2、统一请求模式,使用Restful风格对后端发起请求

3、使用druid数据库连接池技术,进行对数据库连接资源进行管理

4、对已登录的用户使用session进行存储用户信息,登录拦截器拦截的规则就是判断session里有无对应的用户信息来进行拦截

数据库结构

用户表(tb_user) 

订单表(tb_orders)

 

项目文件结构

 

项目效果

登录页

 

首页(展示当前登录用户的订单信息)

 

项目核心文件

Tomcat服务器配置文件 (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文件

<?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文件

<?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文件

<?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文件

<?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文件(这里的数据库配置信息需要改成你自己的,比如密码和驱动)

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

登录拦截器(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控制器

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");
    }

}

最后,无偿给大家整个项目文件,进入《亦码》小程序,找到SSM分类源码

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/95978.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

贤鱼的刷题日常(数据结构栈学习)-1551:Sumsets--题目详解

&#x1f3c6;今日学习目标&#xff1a; &#x1f340;例题讲解1551:Sumsets ✅创作者&#xff1a;贤鱼 ⏰预计时间&#xff1a;25分钟 &#x1f389;个人主页&#xff1a;贤鱼的个人主页 &#x1f525;专栏系列&#xff1a;c &#x1f341;贤鱼的个人社区&#xff0c;欢迎你的…

学Python的理由有哪些?这四大理由足够了

学Python的理由有哪些&#xff1f;可能有人会说Python是一种计算机语言&#xff0c;具有简洁性、易读性、及可扩展性&#xff0c;相对于其他语言学起来会更加容易&#xff0c;目前应用也非常广泛等等。其实总结起来&#xff0c;学Python的理由不外乎四点&#xff0c;即丰富免费…

Python数据分析主要功能是什么?可以用来做什么?

Python是一种计算机程序设计语言&#xff0c;具有简洁性、易读性以及可扩展性&#xff0c;相较于其他语言学习起来更加容易。随着互联网的发展&#xff0c;Python知识也被越来越多的人所熟知。但还是有很多人不了解它究竟可以用来做什么&#xff0c;接下来就跟随我了解一下吧&a…

【轻量级开源ROS 的机器人设备(5)】--(2)拟议的框架——µROS节点

接上文&#xff1a; 【轻量级开源ROS 的机器人设备&#xff08;5&#xff09;】--&#xff08;1&#xff09;拟议的框架——ROS节点 四、开发工具 为了方便用户应用程序的开发&#xff0c;一个代码生成器&#xff0c;一个 堆栈使用分析器和演示项目包含在框架中包裹。 4.1 代…

截止12.17 bitahub踩坑,mask无数次更改,lama代码的那些痛,羊了个羊

前面那篇跑出了STCN&#xff0c;倒是STCN熟悉了很多了 对bitahub&#xff0c;需要注意一个问题 要进ssh请用debug卡&#xff01;&#xff01;&#xff01;&#xff01; 要进ssh请用debug卡&#xff01;&#xff01;&#xff01;&#xff01; 要进ssh请用debug卡&#xff01;&…

数据库文档展示工具

实用工具&#xff1a;数据库文档展示工具 简介 数据库文档展示工具&#xff08;database doc&#xff09;&#xff0c;又叫数据库注释浏览工具&#xff0c;是一个简单的数据库展示各个字段注释的开源工具。在日常开发工作中&#xff0c;您有否这样的体验&#xff1f; 想给前…

干货 | 数字经济创新创业——数字技术创造新经济

下文整理自清华大学大数据能力提升项目能力提升模块课程“Innovation & Entrepreneurship for Digital Economy”&#xff08;数字经济创新创业课程)的精彩内容。主讲嘉宾&#xff1a;Kris Singh: CEO at SRII, Palo Alto, CaliforniaVisiting Professor of Tsinghua Unive…

Elasticsearch 多索引搜索 多条件筛选 去除重复数据

Elasticsearch 多索引搜索 多条件筛选先看结构 分别是索引media_data_es,live_room_essearch_type :dfs_query_then_fetch 不重复复合查询 复合查询就是把一些简单查询组合在一起实现更复杂的查询需求&#xff0c;除此之外&#xff0c;复合查询还可以控制另外一个查询的行为。 …

Spring MVC介绍

Spring MVC 简介什么是Spring MVC了解 MVCMVC 和Spring MVC的联系如何创建一个Spring Web项目在Spring Web 项目中&#xff0c;如何连接Http请求Controller注解可以用其他类注解代替吗连接其他类型的请求如何获取请求中的数据获取单个请求参数获取多个请求参数获取对象获取表单…

高通平台开发系列讲解(DSI篇)DSI层在拨号中的调用逻辑

沉淀、分享、成长,让自己和他人都能有所收获!😄 📢DSI层在拨号中起到的是承上启下的作用。 拨号初始化: 通过mcm_data_init_srv接口调用dsi_init_ex接口,而dsi_init_ex接口进一步通过依次调用dsi_init_cb_func来初始化注册回调、dsi_init_cb_data来初始化数据回调及dsi…

XXL-Job分布式任务调度框架-- 介绍和服务搭建1

一 xxl-job介绍 1.1 xxl-job介绍 xxl-job是轻量级的分布式任务调度框架&#xff0c;目标是开发迅速、简单、清理、易扩展; 老版本是依赖quartz的定时任务触发&#xff0c;在v2.1.0版本开始 移除quartz依 。 分布式任务调度平台XXL-JOB/ 分布式任务调度平台XXL-JOB 二 xxl-…

Prometheus之集成Flink

目录1. 基本介绍2. 拷贝Flink jar包3. 修改Flink的配置文件flink-conf.yaml4. 重启Flink集群5. 验证是否集成成功1. 基本介绍 Flink提供的Metrics可以在Flink内部收集一些指标&#xff0c;通过这些指标让开发人员更 好地查看作业或集群的状态 2. 拷贝Flink jar包 在Flink集群…

[附源码]Node.js计算机毕业设计互联网在线笔记管理系统Express

项目运行 环境配置&#xff1a; Node.js最新版 Vscode Mysql5.7 HBuilderXNavicat11Vue。 项目技术&#xff1a; Express框架 Node.js Vue 等等组成&#xff0c;B/S模式 Vscode管理前后端分离等等。 环境需要 1.运行环境&#xff1a;最好是Nodejs最新版&#xff0c;我…

【C++】list的介绍和使用

​&#x1f320; 作者&#xff1a;阿亮joy. &#x1f386;专栏&#xff1a;《吃透西嘎嘎》 &#x1f387; 座右铭&#xff1a;每个优秀的人都有一段沉默的时光&#xff0c;那段时光是付出了很多努力却得不到结果的日子&#xff0c;我们把它叫做扎根 目录&#x1f449;list 的介…

操作系统原理和接口

这个阶段的课程讲授操作系统的原理和Linux系统给应用层提供的C编程接口。操作系统通过系统调用提供的抽象层是一切中间层和应用软件的根本。 课程建设思路-传统误区 长久以来这个阶段的课程是按照《UNIX环境高级编程》这本书进行讲解的。这个环节的课程甚至曾因此被称为"高…

新能源电动汽车充电桩收费平台

安科瑞 华楠 一、业务模式 平台客户 两种合作方式 1&#xff09;数据托管方式 安科瑞指导用户完成充电桩的安装&#xff0c;用户的充电桩将数据上传至安科瑞充电桩收费运营云平台&#xff0c;委托安科瑞管理&#xff0c;按规定/约定收取托管费用。 2&#xff09;用户自建平…

D-028 DDR3硬件电路设计

DDR3硬件电路设计1 简介2 电路设计3 设计要点1 简介 RAM&#xff08;Random Access Memory&#xff09;是随机存储器&#xff0c;存储单元中的内容可以按需任意去除或者存入&#xff0c;并且存取的速度与存储单元的位置无关。这种存储器在断电时&#xff0c;将丢失其存储的内容…

@Pointcut 的 12 种用法

这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题&#xff0c;有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注…

数据结构---鸡尾酒排序

鸡尾酒排序是基于冒泡排序的一种升级排序法&#xff08;双向冒泡排序&#xff09;冒泡排序&#xff1a;每一轮都是从左到右来比较元素&#xff0c;进行单向的位置交换的。鸡尾酒排序的元素比较和交换过程是双向的。解决的问题如下&#xff1a;从小到大排序{2,3,4,5,6,7,8,1} 如…

微服务框架 SpringCloud微服务架构 多级缓存 48 多级缓存 48.9 Nginx 本地缓存

微服务框架 【SpringCloudRabbitMQDockerRedis搜索分布式&#xff0c;系统详解springcloud微服务技术栈课程|黑马程序员Java微服务】 多级缓存 文章目录微服务框架多级缓存48 多级缓存48.9 Nginx 本地缓存48.9.1 Nginx本地缓存需求48.9.2 Nginx 本地缓存48 多级缓存 48.9 Ng…