采用SSM框架实现登录拦截,分页,批量删除的功能

本案列采用的技术有后端spring/springmvc/mybatis/jquery等技术,前端采用bootstrap+jsp

采用SSM框架实现登录拦截,分页,批量删除的功能_第1张图片

项目结构如下图
采用SSM框架实现登录拦截,分页,批量删除的功能_第2张图片

依赖pom.xml文件

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.18.RELEASE</version>
      <!--      <optional>true</optional>-->
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>


    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>2.0.4</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.2.9</version>
    </dependency>
<!--    分页-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.3.0</version>
    </dependency>
<!--    json依赖-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.9</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.6.7</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.7</version>
    </dependency>

applicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!--    加载properties文件PPC-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="location" value="classpath:jdbc.properties"/>
    </bean>

<!--    配置数据源 DDS-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
<!--    配置mybatis与spring的整合 SSFB-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        关联数据源-->
        <property name="dataSource"  ref="dataSource"/>
<!--        配置别名-->
        <property name="typeAliasesPackage" value="com.mvc.entity"/>
<!--        扫描sqp映射文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!--        配置分页拦截器-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

<!--    mapper动态处理,扫描dao接口MSC-->
    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
<!--        扫描dao接口-->
        <property name="basePackage" value="com.mvc.mapper"/>
    </bean>

<!--    事务管理 DSTM-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>



</beans>

spring-mvc.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:tx="http://www.springframework.org/schema/tx"
       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-3.1.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                         http://www.springframework.org/schema/context
                         http://www.springframework.org/schema/context/spring-context.xsd
                         http://www.springframework.org/schema/mvc
                         http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--        开启spring的扫描-->
<context:component-scan base-package="com.mvc"/>
<!--    开启springmvc的注解-->
<mvc:annotation-driven/>

    <!--    配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**/"/>
            <bean class="com.mvc.utils.LoginInterCerptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

<!--    配置视图路径-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!--        配置页面前缀-->
    <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>

jdbc.properties文件


```cpp
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf8
username=root
password=12345678

web.xml 配置文件


```c
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

  <!--  配置监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--  配置spring核心文件,自动加载-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--  处理乱码-->
  <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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*
  

  
  
    springmvc
    org.springframework.web.servlet.DispatcherServlet
    
    
      contextConfigLocation
      classpath:spring-mvc.xml
    
    
    1
    true
  
  
  
    springmvc
    /
  


数据库脚本

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `userpwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`userid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (4, '小李', '123');
INSERT INTO `user` VALUES (7, '小陈', '123');
INSERT INTO `user` VALUES (8, '小王', '123');
INSERT INTO `user` VALUES (9, '小波波', '123');
INSERT INTO `user` VALUES (10, '小红', '123');
INSERT INTO `user` VALUES (11, '小黄', '123');
INSERT INTO `user` VALUES (12, '小黑', '123');

用户实体类 user
采用SSM框架实现登录拦截,分页,批量删除的功能_第3张图片
dao接口类
采用SSM框架实现登录拦截,分页,批量删除的功能_第4张图片
接口对应的SQL映射文件 UserMapper.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.mvc.mapper.UserMapper">

<!--  查询所有-->
    <select id="selectAll" resultType="user">
        select * from user
    </select>
<!-- 批量删除-->
    <delete id="delAll">
        delete from user where userid in
        <foreach collection="ides" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>
<!--    登录-->
    <select id="login" resultType="user">
        select * from user where username=#{username} and userpwd=#{userpwd}
    </select>

</mapper>

service接口类
采用SSM框架实现登录拦截,分页,批量删除的功能_第5张图片
service接口实现类 UserServiceImpl
采用SSM框架实现登录拦截,分页,批量删除的功能_第6张图片
登录拦截器类LoginInterCerptor


mport com.mvc.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 登录拦截器
 */

public class LoginInterCerptor implements HandlerInterceptor {
    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //获取请求路径中的uri
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();
        //获取登录的对象
        User user = (User) session.getAttribute("loginuser");
        if (uri.indexOf("/login")==0){//放开登录请求
            //放行
            return true;
        }
        if (user!=null){
            return true;
        }
        //不符合条件的
        request.setAttribute("error","请先登录!!!!");
        request.getRequestDispatcher("/login").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
Json数据格式返回统一格式类

```c
package com.mvc.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Result {
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
    // 响应业务状态
    private Integer status;
    // 响应消息
    private String msg;
    // 响应中的数据
    private Object data;

    public Result() {
    }

    public Result(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public Result(Object data) {
        this.status = 0;
        this.msg = "OK";
        this.data = data;
    }

    public static Result ok() {
        return new Result(null);
    }

    public static Result ok(Object data) {
        return new Result(data);
    }

    public static Result build(Integer status, String msg) {
        return new Result(status, msg, null);
    }

    public static Result build(Integer status, String msg, Object data) {
        return new Result(status, msg, data);
    }

    public static ObjectMapper getMAPPER() {
        return MAPPER;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

Controller控制层类 UserController

package com.mvc.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mvc.entity.User;
import com.mvc.service.UserService;
import com.mvc.utils.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;


    @RequestMapping("/login")
    public String login(String username, String userpwd, HttpServletRequest request){
        User user = userService.login(username, userpwd);
        if (user!=null){
            //把user保存到session
            HttpSession session = request.getSession();
            session.setAttribute("loginuser",user);
            //重定向执行列表请求
            return "redirect:/all";
        }else {
            //登录失败返回登录界面
            return "login";
        }

    }

    @RequestMapping("/all")
    public String selectAll(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                            Model model){

        //开始分页
        PageHelper.startPage(pageNum,3);
        //获取数据
        List<User> users = userService.selectAll();
        //包装数据,连续显示3页
        PageInfo<User> pageInfo = new PageInfo<>(users, 3);
        //保存数据
        model.addAttribute("pageInfo",pageInfo);
        return "list";

    }

    //批量删除
    @RequestMapping("/delAll")
    @ResponseBody
    public Result delAll(String ides){
        //把string类型的数组转换成int类型的
        String[] str_id = ides.split(",");
        int[] int_id = new int[str_id.length];
        for (int i = 0;i<str_id.length;i++) {
            int_id[i]=Integer.parseInt(str_id[i]);
        }
        //调用业务方法
        userService.delAll(int_id);
        return Result.build(200,"ok");

    }




}

前端页面结构如下,分别有index.jsp/login.jsp/list.jsp页面
采用SSM框架实现登录拦截,分页,批量删除的功能_第7张图片

jsp index.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h2>景区登录</h2>
<div>
    <form action="/login" method="post" id="login">
        <table>
            <tr>
                <td>用户名</td>
                <td>
                    <input name="username" id="username">
                </td>
            </tr>
            <tr>
                <td>密码</td>
                <td>
                    <input name="userpwd" id="userpwd">
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" id="btn" value="登录">
                    <input type="reset" value="重置">
                </td>
            </tr>
        </table>
    </form>
</div>
</body>
<script>
    $(function () {
        //给登录按钮绑定单击事件
        $("#btn").on("click",function () {
            var errormsg = "";
            var flag = true;
            //获取用户名
            var username = $("#username").val();
            var userpwd = $("#userpwd").val();
            if (username==""||userpwd==""){
                errormsg="用户名或密码不能为空";
                alert(errormsg);
                flag=false;
                return
            }else {
                //提交登录
                $("#login").submit();
            }

        })
    })
</script>
</html>

数据展示页面list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/6/9 0009
  Time: 19:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div>
        <div class="container">
            <button class="btn btn-danger" id="deluser">删除</button>
            <table class="table" border="1" width="567px">
                <tr align="center">
                    <td>编号</td>
                    <td>
                        全选<input type="checkbox" id="all">
                    </td>
                    <td>姓名</td>
                    <td>密码</td>
                    <td>操作</td>
                </tr>
                <c:forEach items="${pageInfo.list}" var="user">
                    <tr align="center">
                        <td>${user.userid}</td>
                        <td>
                            <input type="checkbox" class="userid" value="${user.userid}">
                        </td>
                        <td>${user.username}</td>
                        <td>${user.userpwd}</td>
                        <td>
                            <button><a href="del?userid=${user.userid}">删除</a></button>
                        </td>
                    </tr>
                </c:forEach>
            </table>
        </div>
        <div class="container">
            <ul class="pagination pagination-lg">
                <li class="page-item"><a class="page-link" href="all?pageNum=1">首页</a></li>
                <li class="page-item"><a class="page-link" href="all?pageNum=${pageInfo.pageNum-1}">上一页</a></li>
                <c:forEach items="${pageInfo.navigatepageNums}" var="page">
                    <li class="page-item"><a class="page-link" href="all?pageNum=${page}">${page}</a></li>
                </c:forEach>

                <li class="page-item"><a class="page-link" href="all?pageNum=${pageInfo.pageNum+1}">下一页</a></li>
                <li class="page-item"><a class="page-link" href="all?pageNum=${pageInfo.pages}">末页</a></li>
            </ul>

        </div>
    </div>
</body>
  <script>
      $(function () {

            //给全选按钮绑定单击事件
          $("#all").click(function () {//全选
                $(".userid").prop("checked",this.checked)

          });
          $(".userid").click(function () {
              if ($(".userid").length==$(".userid:checked").length){
                  $("#all").prop("checked",true)
              }else {
                  $("#all").prop("checked",false)
              }
          })
          //删除
          $("#deluser").click(function () {
              var ides = "";
              var userides = $(".userid:checked")
              for(var i =0;i<userides.length;i++){
                  ides+=userides[i].value+","
              }
             $.ajax({
                 url:"/delAll?ides="+ides,
                 type:"post",
                 dataType:"json",
                 success:function (result) {
                     var msg = result.msg;
                     if (msg=="ok"){
                         window.location.href="/all"
                     }

                 }
             })
          })
      })
  </script>
</html>

login.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h2>景区登录</h2>
<div>
    <form action="/login" method="post" id="login">
        <table>
            <tr>
                <td>用户名</td>
                <td>
                    <input name="username" id="username">
                </td>
            </tr>
            <tr>
                <td>密码</td>
                <td>
                    <input name="userpwd" id="userpwd">
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" id="btn" value="登录">
                    <input type="reset" value="重置">
                </td>
            </tr>
        </table>
    </form>
</div>
</body>
<script>
    $(function () {
        //给登录按钮绑定单击事件
        $("#btn").on("click",function () {
            var errormsg = "";
            var flag = true;
            //获取用户名
            var username = $("#username").val();
            var userpwd = $("#userpwd").val();
            if (username==""||userpwd==""){
                errormsg="用户名或密码不能为空";
                alert(errormsg);
                flag=false;
                return
            }else {
                //提交登录
                $("#login").submit();
            }

        })
    })
</script>
</html>

你可能感兴趣的:(SSM框架,java,spring,mybatis)