window.cnblogsConfig = { blogUser: 'MoYu', blogAvatar: 'https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg', blogStartDate: '2020-02-09', webpageTitleOnblur: '(o゚v゚)ノ Hi,Back', webpageTitleOnblurTimeOut: 500, webpageTitleFocus: '(*´∇`*) 欢迎回来!', webpageTitleFocusTimeOut: 1000, webpageIcon: "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg", enable: true, // 是否开启日/夜间模式切换按钮 auto: { // 自动切换相关配置 enable: false, // 开启自动切换 dayHour: 7, // 日间模式开始时间,整数型,24小时制 nightHour: 20 // 夜间模式开始时间,整数型,24小时制 } switchDayNight: { enable: true, auto: { enable: true } }, progressBar: { id : 'top-progress-bar', // 请勿修改该值 color : '#77b6ff', height : '2px', duration: 0.2, }, loading: { rebound: { tension: 16, friction: 5, }, spinner: { id: 'spinner', radius: 90, sides: 3, depth: 4, colors: { background: '#f0f0f0', stroke: '#272633', base: null, child: '#272633', }, alwaysForward: true, // When false the spring will reverse normally. restAt: 0.5, // A number from 0.1 to 0.9 || null for full rotation renderBase: false, } }, homeTopAnimationRendered: true, homeTopAnimation: { radius: 15, density: 0.2, color: 'rgba(255,255,255, .2)', // 颜色设置,“random” 为随机颜色 clearOffset: 0.3, }, essayTopAnimationRendered: true, essayTopAnimation: { triW : 14, triH : 20, neighbours : ["side", "top", "bottom"], speedTrailAppear : .1, speedTrailDisappear : .1, speedTriOpen : 1, trailMaxLength : 30, trailIntervalCreation : 100, delayBeforeDisappear : 2, colorsRandom: false, // v1.2.4 是否开启随机颜色 colors: [ '#96EDA6', '#5BC6A9', '#38668C', '#374D84', '#BED5CB', '#62ADC6', '#8EE5DE', '#304E7B' ] }, homeTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp" ], homeBannerTextType: "one", essayTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190902.jpg", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190954.jpg", ], codeMaxHeight: true, codeLineNumber: true, essayCode: { fontFamily: "'Ubuntu Mono',monospace", // 代码框字体 fontSize: "14px" // 代码框字体大小 }, }

SSM 电影后台管理项目

SSM 电影后台管理项目

概述

通过对数据库中一张表的CRUD,将相应的操作结果渲染到页面上。
笔者通过这篇博客还原了项目(当然有一些隐藏的坑),然后将该项目上传到了GithubGitee,在末尾会附上有源码地址,读者可参考。

该项目使用的是Spring+SpringMVC+Mybaits(SSM)后端架构,POJO---Dao---Service---Controller的结构,简单易懂。

  • POJO:实体类层,封装的是数据中的设计的表对应的元素。
  • Dao:Mapper的接口以及Mapper.xml文件,实现sql操作。
  • Service:服务实现层,调用Dao层方法进行实现。
  • Controller:控制层,调用一个个Service层的实现方法完成一个个具体功能。

项目使用了前端JS检错后端JSR303参数校验,能把绝大部分的问题都包括其中。类似于输入信息错误以及输入信息不合法违规跳转等,也加入了过滤器,使用户可以有更好的体验。

电影后台管理系统的管理员在工作中需要查阅和管理如下信息:后台管理的管理员、电影信息、新闻信息以及类型信息。如下图:

1

准备

  • 环境:
    • IDEA
    • MySQL 5.1.47
    • Tomcat 9
    • Maven 3.6
  • 要求:
    • 掌握MySQL数据库
    • 掌握Spring
    • 掌握MyBatis
    • 掌握SpringMVC
    • 掌握简单的前端知识

实现

1.前置准备

1.1 创建数据库film

CREATE DATABASE `film`;

USE `film`;

-- ----------------------------
-- Table structure for film
-- ----------------------------
DROP TABLE IF EXISTS `film`;
CREATE TABLE `film`  (
  `ISDN` int(20) NOT NULL,
  `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `director` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `actor` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `country` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `language` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `score` double(10, 0) NULL DEFAULT NULL,
  `photo` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `href` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `description` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`ISDN`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of film
-- ----------------------------
INSERT INTO `film` VALUES (1, '神奇女侠', '派蒂·杰金斯', '盖尔·加朵', '科幻', '美国', '英语', 7, 'http://localhost:8080/video/\\sq.png', 'http://localhost:8080/video/\\导入视频.mp4', '故事背景设定在五光十色...');
INSERT INTO `film` VALUES (2, '紧急救援', '林超贤', '彭于晏', '动作', '中国大陆', '汉语普通话', 6, 'http://localhost:8080/video/\\jj.png', 'http://localhost:8080/video/\\导入视频.mp4', '倾覆沉没的钻井平台...');
INSERT INTO `film` VALUES (3, '333333333', '3', '3', '科幻', '3', '4', 3, 'http://localhost:8080/video/\\Snipaste_2020-10-11_00-02-07.png', 'http://localhost:8080/video/\\导入视频.mp4', '111');

-- ----------------------------
-- Table structure for news
-- ----------------------------
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news`  (
  `ISDN` int(11) NOT NULL,
  `title` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `author` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `date` date NULL DEFAULT NULL,
  `description` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`ISDN`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of news
-- ----------------------------
INSERT INTO `news` VALUES (1, 'test1', 'zczc', '2009-01-13', '这是一个测试');
INSERT INTO `news` VALUES (2, 'test2', 'zctoo', '2001-02-15', '这也是一个测试');

-- ----------------------------
-- Table structure for types
-- ----------------------------
DROP TABLE IF EXISTS `types`;
CREATE TABLE `types`  (
  `id` int(11) NOT NULL,
  `type` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of types
-- ----------------------------
INSERT INTO `types` VALUES (1, '科幻');
INSERT INTO `types` VALUES (2, '战争');
INSERT INTO `types` VALUES (3, '历史');
INSERT INTO `types` VALUES (4, '动作');
INSERT INTO `types` VALUES (5, '爱情');
INSERT INTO `types` VALUES (6, '喜剧');
INSERT INTO `types` VALUES (7, '冒险');
INSERT INTO `types` VALUES (8, '恐怖');

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `paw` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `tele` int(20) NULL DEFAULT NULL,
  `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '111111', '123456', 111, 'moyu_zc@13.com');
INSERT INTO `user` VALUES (2, '111zc', 'zc123', 1111111111, '1437101473@qq.com');

SET FOREIGN_KEY_CHECKS = 1;

1.2 导入需要的依赖

<dependencies>
    <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.4.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.jhlabs</groupId>
        <artifactId>filters</artifactId>
        <version>2.0.235</version>
    </dependency>
    <dependency>
        <groupId>com.github.penggle</groupId>
        <artifactId>kaptcha</artifactId>
        <version>2.3.2</version>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.taglibs</groupId>
        <artifactId>taglibs-standard-spec</artifactId>
        <version>1.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.taglibs</groupId>
        <artifactId>taglibs-standard-impl</artifactId>
        <version>1.2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2.1-b03</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.2.Final</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>1.4</version>
    </dependency>
</dependencies>

1.3 Maven资源过滤以及JDK设置

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

1.4 创建好项目架构

先创建好com.zc.xxx路径下的文件;resources资源文件夹下的文件可以先不创建,下面会逐步创建。

2

2.Mybaits

2.1 数据库配置文件

数据库配置文件 db.properties

jabc.driver=com.mysql.jdbc.Driver
jabc.url=jdbc:mysql://localhost:3306/film?useUnicode=true&characterEncoding=UTF-8
jabc.username=root
jabc.password=root

2.2 关联数据库

IDEA关联数据库,用idea登陆上自己的数据库

2.3 编写MyBatis的核心配置文件

MyBatis的核心配置文件:mybatis-config.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>

    <mappers>
        <mapper resource="xxxx"/>     <!-- 写好了Mapper.xml文件,记得第一时间绑定  -->
    </mappers>
    
</configuration>

3.Spring

配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;

3.1 Spring整合Dao层

配置文件名:spring-dao.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"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 配置整合mybatis -->
	<!-- 1.关联数据库文件 -->
	<context:property-placeholder location="classpath:db.properties"/>

	<!-- 2.数据库连接池 -->
	<!--数据库连接池
        dbcp 半自动化操作 不能自动连接
        c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
    -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 配置连接池属性 -->
		<property name="driverClass" value="${jdbc.driver}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>

		<!-- c3p0连接池的私有属性 -->
		<property name="maxPoolSize" value="30"/>
		<property name="minPoolSize" value="10"/>
		<!-- 关闭连接后不自动commit -->
		<property name="autoCommitOnClose" value="false"/>
		<!-- 获取连接超时时间 -->
		<property name="checkoutTimeout" value="10000"/>
		<!-- 当获取连接失败重试次数 -->
		<property name="acquireRetryAttempts" value="2"/>
	</bean>

	<!-- 3.配置SqlSessionFactory对象 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 注入数据库连接池 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
		<property name="configLocation" value="classpath:mybatis-config.xml"/>
	</bean>

	<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 注入sqlSessionFactory -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
		<!-- 给出需要扫描Dao接口包 -->
		<property name="basePackage" value="com.Dao"/>
	</bean>
	
</beans>

3.2 Spring整合Service层

配置文件名:spring-service.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描service相关的bean -->
    <context:component-scan base-package="com.Service" />

    <!--BookServiceImpl注入到IOC容器中-->
    <bean id="BookServiceImpl" class="com.Service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

如果这个文件出错,是因为Spring的几个配置文件没有整合在一起,有两个方法:

一、手动关联

File---Project Structure中:

3

如果三个不在同一个里面,点 “+” 添加文件。

二、语句引用

在配置文件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"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-service.xml"/>
	<import resource="classpath:spring-dao.xml"/>

</beans>

这样这三个xml文件就关联起来了。

4.SpringMVC层

4.1 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
         version="4.0">
    
    <!--DispatcherServlet-->
    <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:applicationContext.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>

    <!--编码配置-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
    
</web-app>

4.2 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/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 1.开启SpringMVC注解驱动 -->
    <mvc:annotation-driven />
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

    <!-- 3.配置jsp 显示ViewResolver视图解析器   这部分加不加自行决定
    <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>
-->
    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.Controller" />

</beans>

4.3 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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

   <import resource="spring-dao.xml"/>
   <import resource="spring-service.xml"/>
   <import resource="spring-mvc.xml"/>
   
</beans>

以上SSM架构,搭建完成

5.POJO层

因为设计的数据库中有4个表,分别是:usertypenewsfilm

所以对应创建四个实体类

public class user {
    private Integer id;
    private String username;
    private String paw;
    private Integer tele;
    private String email;
    // 有参\有参方法
    // Get\Set方法
    // toString()
}
public class types {
    private Integer id;
    private String type;
    // 有参\有参方法
    // Get\Set方法
    // toString()
}

news实体类中使用了JSR303检验机制,不加注解也是可以的

public class news {
    @NotNull
    private Integer ISDN;
    @NotNull
    private String title;
    @NotNull
    private String author;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Past
    private Date date;
    @NotNull
    private String description;
    // 有参\有参方法
    // Get\Set方法
    // toString()
}
public class film {
    private Integer ISDN;
    private String name;
    private String director;
    private String actor;
    private String type;
    private String country;
    private String language;
    private Double score;
    private String photo;
    private String href;
    private String description;
    // 有参\有参方法
    // Get\Set方法
    // toString()
}

在这些实体类中,我使用的是直接添加构造方法;如果觉得麻烦,可以使用Lombok插件

6.Dao层

每一个Dao类都分别对应着一个实体类的操作

Mapper接口+Mapper.xml

6.1 UserMapper

public interface UserMapper {
    /**
     * 获取用户列表
     * @return
     */
    public List<user> getUserList();
    /**
     * id查用户
     * @return
     */
    public user getUserById(int id);
    /**
     *  添加用户
     * @param user
     * @return
     */
   public int insertUser(user user);
    /**
     * 修改用户个人信息
     * @return
     */
   public int upUser(user user);
    /**
     * 修改密码
     * @param user
     * @return
     */
   public int uppaw(user user);
}
<?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.zc.Dao.UserMapper">
    <select id="getUserList" resultType="com.zc.pojo.user">
        select * from film.user
    </select>
    <select id="getUserById" resultType="com.zc.pojo.user">
        select * from film.user where id=#{id}
    </select>
    <insert id="insertUser" parameterType="com.zc.pojo.user" >
        insert into film.user (username,paw,tele,email) values (#{username},#{paw},#{tele},#{email})
    </insert>
    <update id="upUser" parameterType="com.zc.pojo.user">
        update film.user set username = #{username},tele = #{tele},email = #{email} where id = #{id}
    </update>
    <update id="uppaw" parameterType="com.zc.pojo.user">
        update film.user set paw=#{paw} where id = #{id}
    </update>
</mapper>

6.2 TypesMapper

public interface TypesMapper {
    /**
     * 通过ID查找type
     * @param id
     * @return
     */
    public types selectTypeByID(int id);
    /**
     * 查询全部
     * @return
     */
    public List<types> Alltypes();
    /**
     * 通过id删除type
     * @param id
     * @return
     */
    public int DeletetypeById(int id);
    /**
     *  更新type
     * @param types
     * @return
     */
    public int Updatetype(types types);
    /**
     * 添加type
     * @param types
     * @return
     */
    public int addtype(types types);
}

6.3 NewsMapper

public interface NewsMapper {
    /**
     * 通过 ISDN 查找 new
     * @param ISDN
     * @return
     */
    public news selectNewById(int ISDN);
    /**
     *  查询全部新闻
     * @return
     */
    public List<news> Allnews();
    /**
     *  添加新闻
     * @param news
     * @return
     */
    public int addNew(news news);
    /**
     *  更新新闻
     * @param news
     * @return
     */
    public int upNew(news news);
    /**
     * 通过 ISDN 删除新闻
     * @param ISDN
     * @return
     */
    public int DelnewById(int ISDN);
}

6.4 FilmMapper

public interface FilmMapper {
    /**
     *   查找全部电影
     * @return
     */
    public List<film> AllFilm();
    /**
     * 通过ISDN查电影
     * @param ISDN
     * @return
     */
    public List<film> selectfilmByISDN(int ISDN);
    /**
     * 通过导演查电影
     * @param director
     * @return
     */
    public List<film> selectfilmByDir(String director);
    /**
     *  通过类型查电影
     * @param type
     * @return
     */
    public List<film> selectfilmBytype(String type);
    /**
     * 添加电影
     * @param film
     * @return
     */
    public int AddFilm(film film);
    /**
     * 修改电影
     * @param film
     * @return
     */
    public int upFilm(film film);
    /**
     * 通过ISDN 删除电影
     * @param ISDN
     * @return
     */
    public int DelFilm(int ISDN);
}

7.Service层

每个Dao层也会有一个对应的Service实现层

7.1 UserService

public interface UserService {
   /**
    * 得到全部User数据
    * @return
    */
   public  List<user> getUserList();
   /**
    * 插入一个User
    * @param user
    * @return
    */
   public int insertUser(user user);
   /**
    * 更新用户信息
    * @param user
    * @return
    */
   public int upUser(user user);
   /**
    * 更新用户密码
    * @param user
    * @return
    */
   public int uppaw(user user);
   /**
    * 通过id查找用户
    * @param id
    * @return
    */
   public user getUserById(int id);
}
@Service
public class UserServiceimpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<user> getUserList() {
        return userMapper.getUserList();
    }
    @Override
    public int insertUser(user user) {
        return userMapper.insertUser(user);
    }
    @Override
    public int upUser(user user) {
        return userMapper.upUser(user);
    }
    @Override
    public int uppaw(user user) {
        return userMapper.uppaw(user);
    }
    @Override
    public user getUserById(int id) {
        return userMapper.getUserById(id);
    }
}

7.2 TypesService

public interface TypesService {
    /**
     * 通过ID查找type
     * @param id
     * @return
     */
    public types selectTypeByID(int id);
    /**
     * 查询全部
     * @return
     */
    public List<types> Alltypes();
    /**
     * 通过id删除type
     * @param id
     * @return
     */
    public int DeletetypeById(int id);
    /**
     *  更新type
     * @param types
     * @return
     */
    public int Updatetype(types types);
    /**
     * 添加type
     * @param types
     * @return
     */
    public int addtype(types types);
}

7.3 NewsService

public interface NewsService {
    /**
     * 通过 ISDN 查找 new
     * @param ISDN
     * @return
     */
    public news selectNewById(int ISDN);
    /**
     *  查询全部新闻
     * @return
     */
    public List<news> Allnews();
    /**
     *  添加新闻
     * @param news
     * @return
     */
    public int addNew(news news);
    /**
     *  更新新闻
     * @param news
     * @return
     */
    public int upNew(news news);
    /**
     * 通过 ISDN 删除新闻
     * @param ISDN
     * @return
     */
    public int DelnewById(int ISDN);
}

7.4 FilmService

public interface FilmService {
    /**
     *   查找全部电影
     * @return
     */
    public List<film> AllFilm();
    /**
     * 通过ISDN查电影
     * @param ISDN
     * @return
     */
    public List<film> selectfilmByISDN(int ISDN);
    /**
     * 通过导演查电影
     * @param director
     * @return
     */
    public List<film> selectfilmByDir(String director);
    /**
     *  通过类型查电影
     * @param type
     * @return
     */
    public List<film> selectfilmBytype(String type);
    /**
     * 添加电影
     * @param film
     * @return
     */
    public int AddFilm(film film);
    /**
     * 修改电影
     * @param film
     * @return
     */
    public int upFilm(film film);
    /**
     * 通过ISDN 删除电影
     * @param ISDN
     * @return
     */
    public int DelFilm(int ISDN);
}

8.Controller层

Controller层的代码都是实现具体功能的代码

因为代码过长,在此只举例User、types的Controller层代码

@Controller
public class UserController {
    @Autowired
    private   HttpServletRequest request;
    @Autowired
    @Qualifier("userServiceimpl")
    private UserService userService;
    /**
     * 登录
     * @param username
     * @param password
     * @param code
     * @return
     */
    @RequestMapping("/Login")
    public String getUserList(String username, String password, String code){
        List<user> userList = userService.getUserList();
        for (user user : userList) {
            System.out.println(user);
            if(user.getUsername().equals(username)&&user.getPaw().equals(password)){
                HttpSession session = request.getSession();
                Object attribute = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
                if(code.equals(attribute)){
                    session.setAttribute("user",user);
                    return "main.jsp";
                }else {
                    request.setAttribute("mgs", "验证码错误");
                    return "index.jsp";
                }
            }

        }
        //  System.out.println(user.getUsername()+"-----"+user.getPaw());
        request.setAttribute("mgs", "用户名或密码错误");
        return "index.jsp";
    }
    /**
     * 注销
     * @return
     */
    @RequestMapping("/exit")
    public String exit(){
        request.getSession().removeAttribute("user");
        return "index.jsp";
    }
    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public String insertUser(user user){

        List<user> userList = userService.getUserList();
        for (user user1 : userList) {
            if (user1.getUsername().equals(user.getUsername())){
                request.setAttribute("mgs1", "已经存在该用户");
                return "index.jsp";
            }else {
                System.out.println(user);
                userService.insertUser(user);
                return "index.jsp";
            }
        }
        return "index.jsp";
    }
    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @RequestMapping("/upUser")
    public String upUser(user user){
        int i = userService.upUser(user);
        System.out.println(user+"-----"+i);
        if (i>0){
            user user1 = userService.getUserById(user.getId());
            request.getSession().setAttribute("user",user1);
            request.setAttribute("mgs4","修改成功");
            return "person/person_info.jsp";
        }else{
            request.setAttribute("mgs4","修改失败");
            return "person/person_info.jsp";
        }
    }
    /**
     * 修改密码
     * @param user
     * @return
     */
    @RequestMapping("/uppaw")
    public String uppaw(user user, String paw1){
        user userById = userService.getUserById(user.getId());
        System.out.println(user+"----------"+paw1);
        if(userById.getPaw().equals(paw1)){
            userService.uppaw(user);
            user user1 = userService.getUserById(user.getId());
            request.getSession().setAttribute("user",user1);
            request.setAttribute("mgs3","修改密码成功");
            return "person/updatepwd.jsp";
        }else{
            request.setAttribute("mgs3","输入原始密码不对");
            return "person/updatepwd.jsp";
        }
    }
}
@Controller
public class TypesController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    @Qualifier("typesServiceimpl")
    private TypesService typesService;

    /**
     * 查找全部种类
     * @param model
     * @return
     */
    @RequestMapping("/alltypes")
    public String Alltypes(Model model){
        List<types> alltypes = typesService.Alltypes();
        model.addAttribute("alltypes",alltypes);
        return "film/File_cate.jsp";
    }
    /**
     * 添加种类
     * @param types
     * @return
     */
    @RequestMapping("/addtype")
    public String addtype(types types){
        System.out.println(types);
        List<types> alltypes = typesService.Alltypes();
        for (com.zc.pojo.types alltype : alltypes) {
            if (alltype.getId().equals(types.getId())){
                request.setAttribute("addtype","已经存在该电影类别编号");
                return "forward:/alltypes";
            }
            else if (alltype.getType().equals(types.getType())){
                    request.setAttribute("addtype","已经存在该电影类别");
                    return "forward:/alltypes";
            }
        }
        int i = typesService.addtype(types);
        if(i>0){
            request.setAttribute("addtype","添加成功");
            return "forward:/alltypes";
        }else{
            request.setAttribute("addtype","添加失败");
            return "forward:/alltypes";
        }
    }
    /**
     * 更新种类
     * @param types
     * @return
     */
    @RequestMapping("/uptype")
    public String Updatetype(types types){
        List<types> alltypes = typesService.Alltypes();
        for (com.zc.pojo.types alltype : alltypes) {
            if (alltype.getType().equals(types.getType())) {
                request.setAttribute("addtype", "已经存在该电影类别");
                return "forward:/alltypes";
            }
            else {
                int i = typesService.Updatetype(types);
                if(i>0){
                    request.setAttribute("addtype","添加成功");
                    return "forward:/alltypes";
                }else{
                    request.setAttribute("addtype","添加失败");
                    return "forward:/alltypes";
                }
            }
        }
        //System.out.println(types);
        return "forward:/alltypes";
    }
    /**
     * 删除种类
     * @param id
     * @return
     */
    @RequestMapping("/deltype")
    public String Deltype(int id){
        int i = typesService.DeletetypeById(id);
        if(i>0){
            request.setAttribute("addtype","删除成功");
            return "forward:/alltypes";
        }else{
            request.setAttribute("addtype","删除失败");
            return "forward:/alltypes";
        }
    }
}

9.过滤器、拦截器

9.1 过滤器

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String servletPath = request.getServletPath();  //获取客户端所请求的脚本文件的文件路径
        if(servletPath.equals("/index.jsp") ||servletPath.equals("/Login")||servletPath.equals(".js")||servletPath.equals(".css")||servletPath.equals(".png"))
        {
            filterChain.doFilter(request,response);
        }else {
            HttpSession session = request.getSession();
            if (session.getAttribute("user") == null) {
                //  没有登录
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }else {
                filterChain.doFilter(request,response);
            }
        }
    }
    @Override
    public void destroy() {
    }
}

9.2 拦截器

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {
        if (request.getRequestURI().contains(".js")||request.getRequestURI().contains(".css")
            ||request.getRequestURI().contains(".png")||request.getRequestURI().contains(".jpg")) {
            return true;
        }
        HttpSession session = request.getSession();

        if (session.getAttribute("user")!= null) {
            return true;
        }
        request.getRequestDispatcher(request.getContextPath()+"/index.jsp").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 {
    }
}

ApplicationContext.xml中配置:

<mvc:interceptors>
    <mvc:interceptor>
        <!--默认拦截的连接-->
        <mvc:mapping path="/**"/>
        <!--不拦截的连接-->
        <mvc:exclude-mapping path="/Login"/>
        <bean class="com.zc.Fliter.LoginInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

10.项目展示

1 2 3 4 5 6 7 8 9 10

该项目地址为:

Github:https://github.com/MoYu-zc/Film_manage

Gitee:https://gitee.com/MoYu-zc/film_manage

个人博客为:
MoYu's HomePage
MoYu's Gitee Blog

posted @ 2021-03-29 20:40  MoYu-zc  阅读(1509)  评论(0编辑  收藏  举报