日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 综合教程 >内容正文

综合教程

学生管理系统(SSM简易版)总结

發(fā)布時(shí)間:2023/12/19 综合教程 27 生活家
生活随笔 收集整理的這篇文章主要介紹了 学生管理系统(SSM简易版)总结 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

之前用 Servlet + JSP 實(shí)現(xiàn)了一個(gè)簡(jiǎn)易版的學(xué)生管理系統(tǒng),在學(xué)習(xí)了 SSM 框架之后,我們來(lái)對(duì)之前寫過(guò)的項(xiàng)目重構(gòu)一下!

技術(shù)準(zhǔn)備

為了完成這個(gè)項(xiàng)目,需要掌握如下技術(shù):

Java
基礎(chǔ)知識(shí)
前端:
HTML, CSS, JAVASCRIPT, JQUERY
J2EE:
Tomcat, Servlet, JSP, Filter
框架:
Spring, Spring MVC, MyBatis, Spring 與 MyBatis 整合, SSM 整合
數(shù)據(jù)庫(kù):
MySQL
開發(fā)工具:
IDEA, Maven

開發(fā)流程

之前雖然已經(jīng)使用 Servlet + JSP 完成了簡(jiǎn)單的開發(fā),這次使用 SSM 僅僅是重構(gòu)工作,但我們?nèi)匀话凑丈虡I(yè)項(xiàng)目的開發(fā)步驟來(lái)一步一步完成,進(jìn)一步熟悉這個(gè)過(guò)程,重復(fù)的部分我就直接復(fù)制了。

① 需求分析

首先要確定要做哪些功能

使用數(shù)據(jù)庫(kù)來(lái)保存數(shù)據(jù)
增刪改查學(xué)生的信息(學(xué)號(hào),名稱,年齡,性別,出生日期)

② 表結(jié)構(gòu)設(shè)計(jì)

根據(jù)需求,那么只需要一個(gè) student 表就能夠完成功能了。

創(chuàng)建數(shù)據(jù)庫(kù):student
將數(shù)據(jù)庫(kù)編碼格式設(shè)置為 UTF-8 ,便于存取中文數(shù)據(jù)

DROP DATABASE IF EXISTS student;
CREATE DATABASE student DEFAULT CHARACTER SET utf8;

創(chuàng)建學(xué)生表:student
不用學(xué)生學(xué)號(hào)(studentID)作為主鍵的原因是:不方便操作,例如在更新數(shù)據(jù)的時(shí)候,同時(shí)也要更改學(xué)號(hào),那這樣的操作怎么辦呢?
所以我們加了一個(gè) id 用來(lái)唯一表示當(dāng)前數(shù)據(jù)。

CREATE TABLE student(
  id int(11) NOT NULL AUTO_INCREMENT,
  student_id int(11) NOT NULL UNIQUE,
  name varchar(255) NOT NULL,
  age int(11) NOT NULL,
  sex varchar(255) NOT NULL,
  birthday date DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

MySQL 在 Windows 下不區(qū)分大小寫,但在 Linux 下默認(rèn)區(qū)分大小寫,因此,數(shù)據(jù)庫(kù)名、表明、字段名都不允許出現(xiàn)任何大寫字母,避免節(jié)外生枝。

③ 原型設(shè)計(jì)

就是設(shè)計(jì)界面,在商業(yè)項(xiàng)目中,這是很重要的一步,我們可以解除界面原型,低成本、高效率的與客戶達(dá)成需求的一致性

這個(gè)項(xiàng)目一共就分為兩個(gè)頁(yè)面:

主頁(yè)面:

學(xué)生編輯頁(yè)面:

④ SSM 環(huán)境搭建

在真正開始編寫代碼之前,我們首先需要先來(lái)搭建好我們的 SSM 環(huán)境。

第一步:創(chuàng)建 Maven webapp 項(xiàng)目

首先新建工程,選擇 Maven 標(biāo)簽,然后勾選上【Create from archetype】選擇 webapp:

點(diǎn)擊下一步,填寫上【GroupId】和【ArtifactId】:

GroupId:項(xiàng)目組織唯一的標(biāo)識(shí)符,實(shí)際對(duì)應(yīng) JAVA 的包的結(jié)構(gòu),也就是 main 目錄下 java 的目錄結(jié)構(gòu)(包)
AritifactId:項(xiàng)目的唯一標(biāo)識(shí)符,實(shí)際對(duì)應(yīng)項(xiàng)目的名稱,就是項(xiàng)目根目錄的名稱
實(shí)際上你可以亂填上試試,我就不亂填了

然后是確認(rèn)項(xiàng)目路徑,這一步你可以看到 Maven 配置中的參數(shù),不需要做改動(dòng),直接下一步就可以(圖中的路徑是我配置的本地 Maven 倉(cāng)庫(kù)的地址):

確認(rèn)項(xiàng)目名稱和路徑,點(diǎn)擊【Finish】即可:

等待一會(huì)兒,控制臺(tái)就會(huì)有創(chuàng)建成功的提示信息,我們把【Enable Auto-Import】點(diǎn)上,這個(gè)提示會(huì)在每次 pom.xml 有改動(dòng)時(shí)出現(xiàn),自動(dòng)導(dǎo)入,省掉麻煩:

第二步:搭建項(xiàng)目目錄結(jié)構(gòu)

下面就是 Maven 風(fēng)格的 webapp 的默認(rèn)目錄結(jié)構(gòu):

注意: webapp 是默認(rèn)沒(méi)有 java 源文件也沒(méi)有 test 目錄的。

遵循 Maven 的統(tǒng)一項(xiàng)目結(jié)構(gòu),我們搭建出項(xiàng)目的完整目錄結(jié)構(gòu)如下圖:

我們并沒(méi)有使用 Log4j 來(lái)輸出日志,而是使用 logback
提示:我們可以在 IDEA 中右鍵目錄然后選擇【Make Directory as】,讓 IDEA 識(shí)別不同的目錄作用

這里的目錄建好之后還需要設(shè)置一下,讓 IDEA 識(shí)別目錄作用,選擇【File】>【Project Structure】:

設(shè)置好之后點(diǎn)擊 OK,即完成了項(xiàng)目目錄的搭建。

第三步:配置文件內(nèi)容

在【pom.xml】文件中聲明依賴的 jar 包 :

<?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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <name>StudentManagerSSM</name>
    <groupId>cn.wmyskxz</groupId>
    <artifactId>StudentManagerSSM</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.7</version>
                <configuration>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8888</port>
                            <maxIdleTime>30000</maxIdleTime>
                        </connector>
                    </connectors>
                    <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}
                    </webAppSourceDirectory>
                    <contextPath>/</contextPath>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <!-- 設(shè)置項(xiàng)目編碼編碼 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- spring版本號(hào) -->
        <spring.version>4.3.5.RELEASE</spring.version>
        <!-- mybatis版本號(hào) -->
        <mybatis.version>3.4.1</mybatis.version>
    </properties>

    <dependencies>

        <!-- jstl標(biāo)簽 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>


        <!-- java ee -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>

        <!-- 單元測(cè)試 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- 實(shí)現(xiàn)slf4j接口并整合 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.2</version>
        </dependency>

        <!-- JSON -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.7</version>
        </dependency>


        <!-- 數(shù)據(jù)庫(kù) -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
            <scope>runtime</scope>
        </dependency>

        <!-- 數(shù)據(jù)庫(kù)連接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <!-- mybatis/spring整合包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>

</project>

<build> 標(biāo)簽是默認(rèn)生成的
我們?cè)?<properties> 中聲明了編碼格式以及使用的 spring 和 mybatis 的版本號(hào),然后在 <dependencies> 中聲明了具體的 jar 包

在【web.xml】中聲明編碼過(guò)濾器并配置 DispatcherServlet :

<?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_3_1.xsd"
         version="3.1">

    <!-- 編碼過(guò)濾器 -->
    <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>

    <!-- 配置DispatcherServlet -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置springMVC需要加載的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 匹配所有請(qǐng)求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

在【spring-mybatis.xml】中完成 spring 和 mybatis 的配置:

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

    <!-- 掃描service包下所有使用注解的類型 -->
    <context:component-scan base-package="cn.wmyskxz.service"/>

    <!-- 配置數(shù)據(jù)庫(kù)相關(guān)參數(shù)properties的屬性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 數(shù)據(jù)庫(kù)連接池 -->
    <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}"/>
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
    </bean>

    <!-- 配置SqlSessionFactory對(duì)象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數(shù)據(jù)庫(kù)連接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 掃描entity包 使用別名 -->
        <property name="typeAliasesPackage" value="cn.wmyskxz.entity"/>
        <!-- 掃描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置掃描Dao接口包,動(dòng)態(tài)實(shí)現(xiàn)Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出需要掃描Dao接口包 -->
        <property name="basePackage" value="cn.wmyskxz.dao"/>
    </bean>

    <!-- 配置事務(wù)管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入數(shù)據(jù)庫(kù)連接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基于注解的聲明式事務(wù) -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

在【spring-mvc.xml】中完成 Spring MVC 的相關(guān)配置:

<?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
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 掃描web相關(guān)的bean -->
    <context:component-scan base-package="cn.wmyskxz.controller"/>

    <!-- 開啟SpringMVC注解模式 -->
    <mvc:annotation-driven/>

    <!-- 靜態(tài)資源默認(rèn)servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- 配置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/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

在【jdbc.properties】中配置 c3p0 數(shù)據(jù)庫(kù)連接池:

jdbc.driver=com.mysql.jdbc.Driver
#數(shù)據(jù)庫(kù)地址
jdbc.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8
#用戶名
jdbc.username=root
#密碼
jdbc.password=root
#最大連接數(shù)
c3p0.maxPoolSize=30
#最小連接數(shù)
c3p0.minPoolSize=10
#關(guān)閉連接后不自動(dòng)commit
c3p0.autoCommitOnClose=false
#獲取連接超時(shí)時(shí)間
c3p0.checkoutTimeout=10000
#當(dāng)獲取連接失敗重試次數(shù)
c3p0.acquireRetryAttempts=2

在【logback.xml】中完成日志輸出的相關(guān)配置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

以上就完成了 SSM 框架的基本配置:

添加進(jìn)了 SSM 項(xiàng)目所需要的 jar 包
配置好了 spring/mybatis/spring MVC 的相關(guān)配置信息(自動(dòng)掃描 cn.wmyskxz 包下的帶有注解的類)
通過(guò) xml 配置的方式配置好了日志和數(shù)據(jù)庫(kù)

⑤ 實(shí)體類設(shè)計(jì)

實(shí)體類僅僅是對(duì)數(shù)據(jù)庫(kù)中表的一一映射(表中字段名應(yīng)該和實(shí)體類中的名稱一一對(duì)應(yīng)),同時(shí)可能還需要兼顧對(duì)業(yè)務(wù)能力的支持。

在 Packge【cn.wmyskxz.entity】下創(chuàng)建 Student 類:

package cn.wmyskxz.entity;

import java.util.Date;

/**
 * Student 實(shí)體類
 *
 * @author: @我沒(méi)有三顆心臟
 * @create: 2018-04-23-下午 13:34
 */
public class Student {

	private int id;
	private int student_id;
	private String name;
	private int age;
	private String sex;
	private Date birthday;

	/* getter and setter */
}

⑤ DAO 類的設(shè)計(jì)

DAO,即 Date Access Object,數(shù)據(jù)庫(kù)訪問(wèn)對(duì)象,就是對(duì)數(shù)據(jù)庫(kù)相關(guān)操作的封裝,讓其他地方看不到 JDBC 的代碼。

在【cn.wmyskxz.dao】包下創(chuàng)建【StudentDao】接口:

package cn.wmyskxz.dao;

import cn.wmyskxz.entity.Student;

import java.util.List;

public interface StudentDao {
	int getTotal();
	void addStudent(Student student);
	void deleteStudent(int id);
	void updateStudent(Student student);
	Student getStudent(int id);
	List<Student> list(int start, int count);
}

然后在【resources/mapper】下創(chuàng)建好對(duì)應(yīng)的映射文件【StudengDao.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">

<!-- 將namespace的值設(shè)置為DAO類對(duì)應(yīng)的路徑 -->
<mapper namespace="cn.wmyskxz.dao.StudentDao">

    <!-- 查詢數(shù)據(jù)條目 -->
    <select id="getTotal" resultType="int">
        SELECT COUNT(*) FROM student
    </select>

    <!-- 增加一條數(shù)據(jù) -->
    <insert id="addStudent" parameterType="Student">
        INSERT INTO student VALUES(NULL, #{student_id}, #{name}, #{age}, #{sex}, #{birthday})
    </insert>

    <!-- 刪除一條數(shù)據(jù) -->
    <delete id="deleteStudent" parameterType="int">
        DELETE FROM student WHERE id = #{id}
    </delete>

    <!-- 更新一條數(shù)據(jù) -->
    <update id="updateStudent" parameterType="Student">
        UPDATE student SET student_id = #{student_id}, name = #{name},
        age = #{age}, sex = #{sex}, birthday = #{birthday} WHERE id = #{id}
    </update>

    <!-- 查詢一條數(shù)據(jù) -->
    <select id="getStudent" resultMap="student" parameterType="int">
        SELECT * FROM student WHERE id = #{id}
    </select>

    <resultMap id="student" type="student">
        <id column="id" property="id"/>
        <result column="student_id" property="student_id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="sex" property="sex"/>
        <result column="birthday" property="birthday"/>
    </resultMap>

    <!-- 查詢從start位置開始的count條數(shù)據(jù)-->
    <select id="list" resultMap="student">
        SELECT * FROM student ORDER BY student_id desc limit #{param1}, #{param2}
    </select>
</mapper>

編寫好了 Dao 類是需要測(cè)試的,這里測(cè)試類就不給出了。

⑦ 業(yè)務(wù)類設(shè)計(jì)

問(wèn)題: 為什么不直接使用 Dao 類而是還要在上面封裝一層 Service 層呢?
回答:
基于責(zé)任分離的原則,Dao 層就應(yīng)該專注于對(duì)數(shù)據(jù)庫(kù)的操作,而在 Service 層我們可以增加一些非 CRUD 的方法去更好的完成本身抽離出來(lái)的 service 服務(wù)(業(yè)務(wù)處理)。

在【cn.wmyskxz.service】包下創(chuàng)建【StudentService】接口:

package cn.wmyskxz.service;

import cn.wmyskxz.entity.Student;

import java.util.List;

public interface StudentService {

	/**
	 * 獲取到 Student 的總數(shù)
	 * @return
	 */
	int getTotal();

	/**
	 * 增加一條數(shù)據(jù)
	 * @param student
	 */
	void addStudent(Student student);

	/**
	 * 刪除一條數(shù)據(jù)
	 * @param id
	 */
	void deleteStudent(int id);

	/**
	 * 更新一條數(shù)據(jù)
	 * @param student
	 */
	void updateStudent(Student student);

	/**
	 * 找到一條數(shù)據(jù)
	 * @param id
	 * @return
	 */
	Student getStudent(int id);

	/**
	 * 列舉出從 start 位置開始的 count 條數(shù)據(jù)
	 * @param start
	 * @param count
	 * @return
	 */
	List<Student> list(int start, int count);
}

并在相同包名下創(chuàng)建實(shí)現(xiàn)類【StudentServiceImpl】:

package cn.wmyskxz.service;

import cn.wmyskxz.dao.StudentDao;
import cn.wmyskxz.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * StudentService 的實(shí)現(xiàn)類
 *
 * @author: @我沒(méi)有三顆心臟
 * @create: 2018-04-23-下午 13:51
 */
@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	StudentDao studentDao;

	public int getTotal() {
		return studentDao.getTotal();
	}

	public void addStudent(Student student) {
		studentDao.addStudent(student);
	}

	public void deleteStudent(int id) {
		studentDao.deleteStudent(id);
	}

	public void updateStudent(Student student) {
		studentDao.updateStudent(student);
	}

	public Student getStudent(int id) {
		return studentDao.getStudent(id);
	}

	public List<Student> list(int start, int count) {
		return studentDao.list(start, count);
	}
}

⑧ 功能開發(fā)

在【cn.wmyskxz.controller】包下創(chuàng)建【StudentController】控制器,代碼基本上都是復(fù)制黏貼之前在 Servlet 中的代碼:

package cn.wmyskxz.controller;

import cn.wmyskxz.entity.Student;
import cn.wmyskxz.service.StudentService;
import cn.wmyskxz.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Student 控制器
 *
 * @author: @我沒(méi)有三顆心臟
 * @create: 2018-04-23-下午 13:27
 */
@Controller
@RequestMapping("")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping("/addStudent")
	public String addStudent(HttpServletRequest request, HttpServletResponse response) {

		Student student = new Student();

		int studentID = Integer.parseInt(request.getParameter("student_id"));
		String name = request.getParameter("name");
		int age = Integer.parseInt(request.getParameter("age"));
		String sex = request.getParameter("sex");
		Date birthday = null;
		// String 類型按照 yyyy-MM-dd 的格式轉(zhuǎn)換為 java.util.Date 類
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			birthday = simpleDateFormat.parse(request.getParameter("birthday"));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		student.setStudent_id(studentID);
		student.setName(name);
		student.setAge(age);
		student.setSex(sex);
		student.setBirthday(birthday);

		studentService.addStudent(student);

		return "redirect:listStudent";
	}

	@RequestMapping("/listStudent")
	public String listStudent(HttpServletRequest request, HttpServletResponse response) {

		// 獲取分頁(yè)參數(shù)
		int start = 0;
		int count = 10;

		try {
			start = Integer.parseInt(request.getParameter("page.start"));
			count = Integer.parseInt(request.getParameter("page.count"));
		} catch (Exception e) {
		}

		Page page = new Page(start, count);

		List<Student> students = studentService.list(page.getStart(), page.getCount());
		int total = studentService.getTotal();
		page.setTotal(total);

		request.setAttribute("students", students);
		request.setAttribute("page", page);

		return "listStudent";
	}

	@RequestMapping("/deleteStudent")
	public String deleteStudent(int id) {
		studentService.deleteStudent(id);
		return "redirect:listStudent";
	}

	@RequestMapping("/editStudent")
	public ModelAndView editStudent(int id) {
		ModelAndView mav = new ModelAndView("editStudent");
		Student student = studentService.getStudent(id);
		mav.addObject("student", student);
		return mav;
	}

	@RequestMapping("/updateStudent")
	public String updateStudent(HttpServletRequest request, HttpServletResponse response) {

		Student student = new Student();

		int id = Integer.parseInt(request.getParameter("id"));
		int student_id = Integer.parseInt(request.getParameter("student_id"));
		String name = request.getParameter("name");
		int age = Integer.parseInt(request.getParameter("age"));
		String sex = request.getParameter("sex");

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date birthday = null;
		try {
			birthday = simpleDateFormat.parse(request.getParameter("birthday"));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		student.setId(id);
		student.setStudent_id(student_id);
		student.setName(name);
		student.setAge(age);
		student.setSex(sex);
		student.setBirthday(birthday);

		studentService.updateStudent(student);
		return "redirect:listStudent";
	}
}

注意: 所有的學(xué)號(hào)都用 student_id 表示,為了契合在數(shù)據(jù)庫(kù)中的字段名(包括下面的 JSP 文件)

JSP 文件也直接黏之前的就好了,不過(guò)需要注意所有的 name 屬性

【listStudent.jsp】:

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head>

    <%-- 引入JQ和Bootstrap --%>
    <script src="js/jquery/2.0.0/jquery.min.js"></script>
    <link href="css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap/3.3.6/bootstrap.min.js"></script>
    <link href="css/style.css" rel="stylesheet">

    <title>學(xué)生管理頁(yè)面 - 首頁(yè)</title>

    <script>
        $(function () {
            $("ul.pagination li.disabled a").click(function () {
                return false;
            });
        });
    </script>
</head>

<body>

<div class="listDIV">
    <table class="table table-striped table-bordered table-hover table-condensed">

        <caption>學(xué)生列表 - 共${page.total}人</caption>
        <thead>
        <tr class="success">
            <th>學(xué)號(hào)</th>
            <th>姓名</th>
            <th>年齡</th>
            <th>性別</th>
            <th>出生日期</th>

            <th>編輯</th>
            <th>刪除</th>
        </tr>
        </thead>

        <tbody>
        <c:forEach items="${students}" var="s" varStatus="status">
            <tr>
                <td>${s.student_id}</td>
                <td>${s.name}</td>
                <td>${s.age}</td>
                <td>${s.sex}</td>
                <td>${s.birthday}</td>

                <td><a href="/editStudent?id=${s.id}"><span class="glyphicon glyphicon-edit"></span> </a></td>
                <td><a href="/deleteStudent?id=${s.id}"><span class="glyphicon glyphicon-trash"></span> </a></td>
            </tr>
        </c:forEach>

        </tbody>
    </table>
</div>

<nav class="pageDIV">
    <ul class="pagination">
        <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
            <a href="?page.start=0">
                <span>?</span>
            </a>
        </li>

        <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
            <a href="?page.start=${page.start-page.count}">
                <span>?</span>
            </a>
        </li>

        <c:forEach begin="0" end="${page.totalPage-1}" varStatus="status">

            <c:if test="${status.count*page.count-page.start<=30 && status.count*page.count-page.start>=-10}">
                <li <c:if test="${status.index*page.count==page.start}">class="disabled"</c:if>>
                    <a
                            href="?page.start=${status.index*page.count}"
                            <c:if test="${status.index*page.count==page.start}">class="current"</c:if>
                    >${status.count}</a>
                </li>
            </c:if>
        </c:forEach>

        <li <c:if test="${!page.hasNext}">class="disabled"</c:if>>
            <a href="?page.start=${page.start+page.count}">
                <span>?</span>
            </a>
        </li>
        <li <c:if test="${!page.hasNext}">class="disabled"</c:if>>
            <a href="?page.start=${page.last}">
                <span>?</span>
            </a>
        </li>
    </ul>
</nav>

<div class="addDIV">

    <div class="panel panel-success">
        <div class="panel-heading">
            <h3 class="panel-title">增加學(xué)生</h3>
        </div>
        <div class="panel-body">

            <form method="post" action="/addStudent" role="form">
                <table class="addTable">
                    <tr>
                        <td>學(xué)號(hào):</td>
                        <td><input type="text" name="student_id" id="student_id" placeholder="請(qǐng)?jiān)谶@里輸入學(xué)號(hào)"></td>
                    </tr>
                    <tr>
                        <td>姓名:</td>
                        <td><input type="text" name="name" id="name" placeholder="請(qǐng)?jiān)谶@里輸入名字"></td>
                    </tr>
                    <tr>
                        <td>年齡:</td>
                        <td><input type="text" name="age" id="age" placeholder="請(qǐng)?jiān)谶@里輸入年齡"></td>
                    </tr>
                    <tr>
                        <td>性別:</td>
                        <td><input type="radio" class="radio radio-inline" name="sex" value="男"> 男
                            <input type="radio" class="radio radio-inline" name="sex" value="女"> 女
                        </td>
                    </tr>
                    <tr>
                        <td>出生日期:</td>
                        <td><input type="date" name="birthday" id="birthday" placeholder="請(qǐng)?jiān)谶@里輸入出生日期"></td>
                    </tr>
                    <tr class="submitTR">
                        <td colspan="2" align="center">
                            <button type="submit" class="btn btn-success">提 交</button>
                        </td>

                    </tr>

                </table>
            </form>
        </div>
    </div>

</div>


</body>
</html>

【editStudent.jsp】:

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>

    <%-- 引入JQ和Bootstrap --%>
    <script src="js/jquery/2.0.0/jquery.min.js"></script>
    <link href="css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap/3.3.6/bootstrap.min.js"></script>
    <link href="css/style.css" rel="stylesheet">

    <title>學(xué)生管理頁(yè)面 - 編輯頁(yè)面</title>
</head>

<body>

<div class="editDIV">

    <div class="panel panel-success">
        <div class="panel-heading">
            <h3 class="panel-title">編輯學(xué)生</h3>
        </div>
        <div class="panel-body">

            <form method="post" action="/updateStudent" role="form">
                <table class="editTable">
                    <tr>
                        <td>學(xué)號(hào):</td>
                        <td><input type="text" name="student_id" id="student_id" value="${student.student_id}"
                                   placeholder="請(qǐng)?jiān)谶@里輸入學(xué)號(hào)"></td>
                    </tr>
                    <tr>
                        <td>姓名:</td>
                        <td><input type="text" name="name" id="name" value="${student.name}" placeholder="請(qǐng)?jiān)谶@里輸入名字">
                        </td>
                    </tr>
                    <tr>
                        <td>年齡:</td>
                        <td><input type="text" name="age" id="age" value="${student.age}" placeholder="請(qǐng)?jiān)谶@里輸入年齡"></td>
                    </tr>
                    <tr>
                        <td>性別:</td>
                        <td><input type="radio" class="radio radio-inline" name="sex" value="男"> 男
                            <input type="radio" class="radio radio-inline" name="sex" value="女"> 女
                        </td>
                    </tr>
                    <tr>
                        <td>出生日期:</td>
                        <td><input type="date" name="birthday" id="birthday" value="${student.birthday}"
                                   placeholder="請(qǐng)?jiān)谶@里輸入出生日期"></td>
                    </tr>
                    <tr class="submitTR">
                        <td colspan="2" align="center">
                            <input type="hidden" name="id" value="${student.id}">
                            <button type="submit" class="btn btn-success">提 交</button>
                        </td>

                    </tr>

                </table>
            </form>
        </div>
    </div>

</div>

</body>
</html>

style.css 文件:

body {
    padding-top: 60px;
}

div.listDIV {
     600px;
    margin: 0 auto;
}

div.editDIV {
     400px;
    margin: 0 auto;
}

nav.pageDIV {
    text-align: center;
}

div.addDIV {
     300px;
    margin: 0 auto;
}

table.addTable {
     100%;
    padding: 5px;
}

table.addTable td {
    padding: 5px;
}

table.editTable {
     100%;
    padding: 5px;
}

table.editTable td {
    padding: 5px;
}

項(xiàng)目的整體結(jié)構(gòu)

分頁(yè)功能

首先在 Packge【util】包下創(chuàng)建一個(gè) Page 工具類:

package cn.wmyskxz.util;

public class Page {

	int start;		// 開始數(shù)據(jù)
	int count;		// 每一頁(yè)的數(shù)量
	int total;		// 總共的數(shù)據(jù)量

	public Page(int start, int count) {
		super();
		this.start = start;
		this.count = count;
	}

	public boolean isHasPreviouse(){
		if(start==0)
			return false;
		return true;

	}
	public boolean isHasNext(){
		if(start==getLast())
			return false;
		return true;
	}

	public int getTotalPage(){
		int totalPage;
		// 假設(shè)總數(shù)是50,是能夠被5整除的,那么就有10頁(yè)
		if (0 == total % count)
			totalPage = total /count;
			// 假設(shè)總數(shù)是51,不能夠被5整除的,那么就有11頁(yè)
		else
			totalPage = total / count + 1;

		if(0==totalPage)
			totalPage = 1;
		return totalPage;

	}

	public int getLast(){
		int last;
		// 假設(shè)總數(shù)是50,是能夠被5整除的,那么最后一頁(yè)的開始就是40
		if (0 == total % count)
			last = total - count;
			// 假設(shè)總數(shù)是51,不能夠被5整除的,那么最后一頁(yè)的開始就是50
		else
			last = total - total % count;

		last = last<0?0:last;
		return last;
	}

    // 各種 setter 和 getter
}

totalPage 是計(jì)算得來(lái)的數(shù),用來(lái)表示頁(yè)碼一共的數(shù)量

在首頁(yè)顯示的 StudentList 用 page 的參數(shù)來(lái)獲取:

List<Student> students = studentService.list(page.getStart(), page.getCount());

并且在映射文件中用 LIMIT 關(guān)鍵字:

<!-- 查詢從start位置開始的count條數(shù)據(jù)-->
<select id="list" resultMap="student">
    SELECT * FROM student ORDER BY student_id desc limit #{param1}, #{param2}
</select>

第一個(gè)參數(shù)為 start,第二個(gè)參數(shù)為 count
這樣就能根據(jù)分頁(yè)的信息來(lái)獲取到響應(yīng)的數(shù)據(jù)

編寫分頁(yè)欄:

1.寫好頭和尾

<nav class="pageDIV">
    <ul class="pagination">
    .....
    </ul>
</nav>

2.寫好? ?這兩個(gè)功能按鈕
使用 <c:if>標(biāo)簽來(lái)增加邊界判斷,如果沒(méi)有前面的頁(yè)碼了則設(shè)置為disable狀態(tài)

        <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
            <a href="?page.start=0">
                <span>?</span>
            </a>
        </li>

        <li <c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
            <a href="?page.start=${page.start-page.count}">
                <span>?</span>
            </a>
        </li>

再通過(guò) JavaScrip 代碼來(lái)完成禁用功能:

<script>
    $(function () {
        $("ul.pagination li.disabled a").click(function () {
            return false;
        });
    });
</script>

3.完成中間頁(yè)碼的編寫
0 循環(huán)到 page.totalPage - 1varStatus 相當(dāng)于是循環(huán)變量

status.count 是從1開始遍歷
status.index 是從0開始遍歷
要求:顯示當(dāng)前頁(yè)碼的前兩個(gè)和后兩個(gè)就可,例如當(dāng)前頁(yè)碼為3的時(shí)候,就顯示 1 2 3(當(dāng)前頁(yè)) 4 5 的頁(yè)碼
理解測(cè)試條件:
-10 <= 當(dāng)前頁(yè)*每一頁(yè)顯示的數(shù)目 - 當(dāng)前頁(yè)開始的數(shù)據(jù)編號(hào) <= 30

只要理解了這個(gè)判斷條件,其他的就都好理解了

<c:forEach begin="0" end="${page.totalPage-1}" varStatus="status">

    <c:if test="${status.count*page.count-page.start<=30 && status.count*page.count-page.start>=-10}">
        <li <c:if test="${status.index*page.count==page.start}">class="disabled"</c:if>>
            <a
                    href="?page.start=${status.index*page.count}"
                    <c:if test="${status.index*page.count==page.start}">class="current"</c:if>
            >${status.count}</a>
        </li>
    </c:if>
</c:forEach>

4.在控制器中獲取參數(shù)

// 獲取分頁(yè)參數(shù)
int start = 0;
int count = 10;

try {
	start = Integer.parseInt(request.getParameter("page.start"));
	count = Integer.parseInt(request.getParameter("page.count"));
} catch (Exception e) {
}

....

// 共享 page 數(shù)據(jù)
request.setAttribute("page", page);

Date 轉(zhuǎn)換的問(wèn)題

最開始的時(shí)候,我們看到頁(yè)面上顯示的日期是這樣的格式:

這顯然是我們不希望看到的

解決方案:在映射文件中設(shè)置日期顯示的類型。

重新部署文件,然后刷新頁(yè)面,就能看到我們希望的效果啦:

項(xiàng)目總結(jié)

由于之前的項(xiàng)目代碼都有,所以在重構(gòu)的時(shí)候,基本上沒(méi)有花什么時(shí)間就完成了項(xiàng)目的搭建,能夠體會(huì)到代碼分離的重要性,這在很大程度上保證了我們的代碼復(fù)用。
相較于之前用 Servlet + JSP 來(lái)完成,很明顯的感覺(jué)是DAO層的編寫方便了很多,僅僅需要編寫一個(gè) xml 映射文件和一個(gè) Dao 層接口就可以完成功能,而不用自己再去重復(fù)的去在每一個(gè) CRUD 方法中去處理結(jié)果集,重復(fù)而且繁瑣。
注解真的很方便,這不僅僅提升了我們自身開發(fā)的效率,寫起來(lái)也很帶勁兒。
開發(fā)效率快,而且低耦合,我們基于 xml 配置了大部分的工作,在基于 SSM 框架開發(fā)時(shí),我們可以把專注點(diǎn)集中在邏輯處理上。
在 SSM 框架中能方便的對(duì)項(xiàng)目進(jìn)行修改,這不僅僅得益于框架的約定,使得代碼分離并且可復(fù)用,也得益于 Maven 工具對(duì)于項(xiàng)目的管理。
我們能夠通過(guò)一個(gè) Controller 來(lái)完成五個(gè) Servlet 的功能,并且通過(guò)注解來(lái)完成配置。


項(xiàng)目改進(jìn)

項(xiàng)目很簡(jiǎn)單,僅僅也只是在數(shù)據(jù)庫(kù)增刪改查的基礎(chǔ)上增加了一個(gè)界面,我們來(lái)動(dòng)手改一改。

改進(jìn)一:增加刪除提示

第一個(gè)想到的就是刪除提示,沒(méi)有刪除提示是很要命的一件事情,如果手滑了一下那可能就悲劇了....

首先我們?cè)陧敳康?<head> 標(biāo)簽中的 <script> 中增加一段代碼:

function del() {
    var msg = "您真的確定要?jiǎng)h除嗎?

請(qǐng)確認(rèn)!";
    if (confirm(msg) == true) {
        return true;
    } else {
        return false;
    }
}

然后在刪除 a 標(biāo)簽頁(yè)中增加 onclick 屬性:

onclick="javascript:return del();"
....就像下面這樣....
td><a href="/deleteStudent?id=${s.id}" onclick="javascript:return del();"><span
        class="glyphicon glyphicon-trash"></span> </a></td>

當(dāng)我們刷新頁(yè)面后,點(diǎn)擊刪除就會(huì)彈出提示信息:

改進(jìn)二:編輯頁(yè)面自動(dòng)勾選上性別

在當(dāng)前的項(xiàng)目中,如果點(diǎn)擊編輯按鈕進(jìn)入到編輯頁(yè)面后,性別這個(gè)選項(xiàng)是空選的狀態(tài),這就很low:

這個(gè)也很簡(jiǎn)單,在 editStudent 頁(yè)面增加一些判斷就好了:

<c:if> 標(biāo)簽來(lái)判斷 sex 的值,然后根據(jù)對(duì)應(yīng)的屬性增加 checked 屬性,這樣就可以自動(dòng)勾選上所對(duì)應(yīng)的屬性:

改進(jìn)三:空值判斷

我們?cè)试S設(shè)置為 null 的值僅僅為出生日期,其他的值均不允許出現(xiàn)空值,所以我們需要加入空值判斷:

function checkEmpty(id, name) {
    var value = $("#" + id).val();
    if (value.length == 0) {
        alert(name + "不能為空");
        $("#" + id).focus();
        return false;
    }
    return true;
}

然后再為 form 創(chuàng)建一個(gè) id 屬性值為 “addForm” 并添加進(jìn)判斷空值的方法:

注意: 這里需要寫在 $(function(){}) 里面,等待文檔加載完畢才能生效。
這里并沒(méi)有為 sex 屬性判斷空值,我們采用一個(gè)簡(jiǎn)單的為 sex 添加一個(gè)默認(rèn)勾選項(xiàng)來(lái)省略空值的判斷。

同樣的,我們也在編輯頁(yè)面,采用同樣的方法進(jìn)行空值判斷:

當(dāng)進(jìn)入編輯頁(yè)面的時(shí)候已經(jīng)有默認(rèn)的勾選項(xiàng)了,所以 sex 值仍然不需要判空
最后給出項(xiàng)目地址:https://github.com/wmyskxz/StudentManager-SSM

歡迎轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)注明出處!
簡(jiǎn)書ID:@我沒(méi)有三顆心臟
github:wmyskxz
歡迎關(guān)注公眾微信號(hào):wmyskxz_javaweb
分享自己的Java Web學(xué)習(xí)之路以及各種Java學(xué)習(xí)資料

總結(jié)

以上是生活随笔為你收集整理的学生管理系统(SSM简易版)总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。