學生管理系統(SSM簡易版)總結

技術準備

爲了完成這個項目,須要掌握以下技術:javascript

開發流程

以前雖然已經使用 Servlet + JSP 完成了簡單的開發,此次使用 SSM 僅僅是重構工做,但咱們仍然按照商業項目的開發步驟來一步一步完成,進一步熟悉這個過程,重複的部分我就直接複製了。css

① 需求分析

首先要肯定要作哪些功能html

  • 使用數據庫保存數據
  • 增刪改查學生的信息(學號,名稱,年齡,性別,出生日期)

② 表結構設計

根據需求,那麼只須要一個 student 表就可以完成功能了。前端

  • 建立數據庫:student
    將數據庫編碼格式設置爲 UTF-8 ,便於存取中文數據java

    DROP DATABASE IF EXISTS student;
    CREATE DATABASE student DEFAULT CHARACTER SET utf8;
  • 建立學生表:student
    不用學生學號(studentID)做爲主鍵的緣由是:不方便操做,例如在更新數據的時候,同時也要更改學號,那這樣的操做怎麼辦呢?
    因此咱們加了一個 id 用來惟一表示當前數據。mysql

    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 下不區分大小寫,但在 Linux 下默認區分大小寫,所以,數據庫名、代表、字段名都不容許出現任何大寫字母,避免節外生枝。jquery

③ 原型設計

就是設計界面,在商業項目中,這是很重要的一步,咱們能夠解除界面原型,低成本、高效率的與客戶達成需求的一致性git

這個項目一共就分爲兩個頁面:github

  • 主頁面:
    首頁web

  • 學生編輯頁面:
    編輯頁面

④ SSM 環境搭建

在真正開始編寫代碼以前,咱們首先須要先來搭建好咱們的 SSM 環境。

第一步:建立 Maven webapp 項目

首先新建工程,選擇 Maven 標籤,而後勾選上【Create from archetype】選擇 webapp:

點擊下一步,填寫上【GroupId】和【ArtifactId】:

  • GroupId:項目組織惟一的標識符,實際對應 JAVA 的包的結構,也就是 main 目錄下 java 的目錄結構(包)
  • AritifactId:項目的惟一標識符,實際對應項目的名稱,就是項目根目錄的名稱
  • 實際上你能夠亂填上試試,我就不亂填了

而後是確認項目路徑,這一步你能夠看到 Maven 配置中的參數,不須要作改動,直接下一步就能夠(圖中的路徑是我配置的本地 Maven 倉庫的地址):

確認項目名稱和路徑,點擊【Finish】便可:

等待一下子,控制檯就會有建立成功的提示信息,咱們把【Enable Auto-Import】點上,這個提示會在每次 pom.xml 有改動時出現,自動導入,省掉麻煩:

第二步:搭建項目目錄結構

下面就是 Maven 風格的 webapp 的默認目錄結構:

  • 注意: webapp 是默認沒有 java 源文件也沒有 test 目錄的。

遵循 Maven 的統一項目結構,咱們搭建出項目的完整目錄結構以下圖:

  • 咱們並無使用 Log4j 來輸出日誌,而是使用 logback
  • 提示:咱們能夠在 IDEA 中右鍵目錄而後選擇【Make Directory as】,讓 IDEA 識別不一樣的目錄做用

這裏的目錄建好以後還須要設置一下,讓 IDEA 識別目錄做用,選擇【File】>【Project Structure】:

設置好以後點擊 OK,即完成了項目目錄的搭建。

第三步:配置文件內容

在【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>
        <!-- 設置項目編碼編碼 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- spring版本號 -->
        <spring.version>4.3.5.RELEASE</spring.version>
        <!-- mybatis版本號 -->
        <mybatis.version>3.4.1</mybatis.version>
    </properties>

    <dependencies>

        <!-- jstl標籤 -->
        <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>

        <!-- 單元測試 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- 實現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>


        <!-- 數據庫 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
            <scope>runtime</scope>
        </dependency>

        <!-- 數據庫鏈接池 -->
        <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> 標籤是默認生成的
  • 咱們在 <properties> 中聲明瞭編碼格式以及使用的 spring 和 mybatis 的版本號,而後在 <dependencies> 中聲明瞭具體的 jar 包

在【web.xml】中聲明編碼過濾器並配置 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">

    <!-- 編碼過濾器 -->
    <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>
        <!-- 匹配全部請求 -->
        <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"/>

    <!-- 配置數據庫相關參數properties的屬性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 數據庫鏈接池 -->
    <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對象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據庫鏈接池 -->
        <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接口包,動態實現Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出須要掃描Dao接口包 -->
        <property name="basePackage" value="cn.wmyskxz.dao"/>
    </bean>

    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入數據庫鏈接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基於註解的聲明式事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

在【spring-mvc.xml】中完成 Spring MVC 的相關配置:

<?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相關的bean -->
    <context:component-scan base-package="cn.wmyskxz.controller"/>

    <!-- 開啓SpringMVC註解模式 -->
    <mvc:annotation-driven/>

    <!-- 靜態資源默認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 數據庫鏈接池:

jdbc.driver=com.mysql.jdbc.Driver
#數據庫地址
jdbc.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8
#用戶名
jdbc.username=root
#密碼
jdbc.password=root
#最大鏈接數
c3p0.maxPoolSize=30
#最小鏈接數
c3p0.minPoolSize=10
#關閉鏈接後不自動commit
c3p0.autoCommitOnClose=false
#獲取鏈接超時時間
c3p0.checkoutTimeout=10000
#當獲取鏈接失敗重試次數
c3p0.acquireRetryAttempts=2

在【logback.xml】中完成日誌輸出的相關配置:

<?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 框架的基本配置:

  • 添加進了 SSM 項目所須要的 jar 包
  • 配置好了 spring/mybatis/spring MVC 的相關配置信息(自動掃描 cn.wmyskxz 包下的帶有註解的類)
  • 經過 xml 配置的方式配置好了日誌和數據庫

⑤ 實體類設計

實體類僅僅是對數據庫中表的一一映射(表中字段名應該和實體類中的名稱一一對應),同時可能還須要兼顧對業務能力的支持。

  • 在 Packge【cn.wmyskxz.entity】下建立 Student 類:
package cn.wmyskxz.entity;

import java.util.Date;

/**
•Student 實體類
 */
 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 類的設計

DAO,即 Date Access Object,數據庫訪問對象,就是對數據庫相關操做的封裝,讓其餘地方看不到 JDBC 的代碼。

在【cn.wmyskxz.dao】包下建立【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】下建立好對應的映射文件【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的值設置爲DAO類對應的路徑 -->
<mapper namespace="cn.wmyskxz.dao.StudentDao">

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

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

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

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

    <!-- 查詢一條數據 -->
    <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條數據-->
    <select id="list" resultMap="student">
        SELECT * FROM student ORDER BY student_id desc limit #{param1}, #{param2}
    </select>
</mapper>

編寫好了 Dao 類是須要測試的,這裏測試類就不給出了。

⑦ 業務類設計

  • 問題: 爲何不直接使用 Dao 類而是還要在上面封裝一層 Service 層呢?
  • 回答:
    基於責任分離的原則,Dao 層就應該專一於對數據庫的操做,而在 Service 層咱們能夠增長一些非 CRUD 的方法去更好的完成自己抽離出來的 service 服務(業務處理)。

在【cn.wmyskxz.service】包下建立【StudentService】接口:

package cn.wmyskxz.service;

import cn.wmyskxz.entity.Student;

import java.util.List;

public interface StudentService {

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

    /**
     * 增長一條數據
     * @param student
     */
    void addStudent(Student student);

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

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

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

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

並在相同包名下建立實現類【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 的實現類
 *
 * @author: @我沒有三顆心臟
 * @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);
    }
}

⑧ 功能開發

在【cn.wmyskxz.controller】包下建立【StudentController】控制器,代碼基本上都是複製黏貼以前在 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: @我沒有三顆心臟
 * @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 的格式轉換爲 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) {

        // 獲取分頁參數
        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";
    }
}
  • 注意: 全部的學號都用 student_id 表示,爲了契合在數據庫中的字段名(包括下面的 JSP 文件)

JSP 文件也直接黏以前的就行了,不過須要注意全部的 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>學生管理頁面 - 首頁</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>學生列表 - 共${page.total}人</caption>
        <thead>
        <tr class="success">
            <th>學號</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">增長學生</h3>
        </div>
        <div class="panel-body">

            <form method="post" action="/addStudent" role="form">
                <table class="addTable">
                    <tr>
                        <td>學號:</td>
                        <td><input type="text" name="student_id" id="student_id" placeholder="請在這裏輸入學號"></td>
                    </tr>
                    <tr>
                        <td>姓名:</td>
                        <td><input type="text" name="name" id="name" placeholder="請在這裏輸入名字"></td>
                    </tr>
                    <tr>
                        <td>年齡:</td>
                        <td><input type="text" name="age" id="age" placeholder="請在這裏輸入年齡"></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="請在這裏輸入出生日期"></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>學生管理頁面 - 編輯頁面</title>
</head>

<body>

<div class="editDIV">

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

            <form method="post" action="/updateStudent" role="form">
                <table class="editTable">
                    <tr>
                        <td>學號:</td>
                        <td><input type="text" name="student_id" id="student_id" value="${student.student_id}"
                                   placeholder="請在這裏輸入學號"></td>
                    </tr>
                    <tr>
                        <td>姓名:</td>
                        <td><input type="text" name="name" id="name" value="${student.name}" placeholder="請在這裏輸入名字">
                        </td>
                    </tr>
                    <tr>
                        <td>年齡:</td>
                        <td><input type="text" name="age" id="age" value="${student.age}" placeholder="請在這裏輸入年齡"></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="請在這裏輸入出生日期"></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 {
    width: 600px;
    margin: 0 auto;
}

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

nav.pageDIV {
    text-align: center;
}

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

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

table.addTable td {
    padding: 5px;
}

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

table.editTable td {
    padding: 5px;
}

項目的總體結構

分頁功能

  • 首先在 Packge【util】包下建立一個 Page 工具類:
package cn.wmyskxz.util;

public class Page {

    int start;      // 開始數據
    int count;      // 每一頁的數量
    int total;      // 總共的數據量

    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;
        // 假設總數是50,是可以被5整除的,那麼就有10頁
        if (0 == total % count)
            totalPage = total /count;
            // 假設總數是51,不可以被5整除的,那麼就有11頁
        else
            totalPage = total / count + 1;

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

    }

    public int getLast(){
        int last;
        // 假設總數是50,是可以被5整除的,那麼最後一頁的開始就是40
        if (0 == total % count)
            last = total - count;
            // 假設總數是51,不可以被5整除的,那麼最後一頁的開始就是50
        else
            last = total - total % count;

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

    // 各類 setter 和 getter
}
  • totalPage 是計算得來的數,用來表示頁碼一共的數量

在首頁顯示的 StudentList 用 page 的參數來獲取:

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

而且在映射文件中用 LIMIT 關鍵字:

<!-- 查詢從start位置開始的count條數據-->
<select id="list" resultMap="student">
    SELECT * FROM student ORDER BY student_id desc limit #{param1}, #{param2}
</select>
  • 第一個參數爲 start,第二個參數爲 count
    這樣就能根據分頁的信息來獲取到響應的數據

  • 編寫分頁欄:

1.寫好頭和尾

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

2.寫好« 這兩個功能按鈕
使用 <c:if>標籤來增長邊界判斷,若是沒有前面的頁碼了則設置爲disable狀態

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

再經過 JavaScrip 代碼來完成禁用功能:

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

3.完成中間頁碼的編寫
0 循環到 page.totalPage - 1varStatus 至關因而循環變量

  • status.count 是從1開始遍歷
  • status.index 是從0開始遍歷
  • 要求:顯示當前頁碼的前兩個和後兩個就可,例如當前頁碼爲3的時候,就顯示 1 2 3(當前頁) 4 5 的頁碼
  • 理解測試條件:
    -10 <= 當前頁*每一頁顯示的數目 - 當前頁開始的數據編號 <= 30

  • 只要理解了這個判斷條件,其餘的就都好理解了
<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.在控制器中獲取參數

// 獲取分頁參數
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 數據
request.setAttribute("page", page);

Date 轉換的問題

最開始的時候,咱們看到頁面上顯示的日期是這樣的格式:

這顯然是咱們不但願看到的

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

從新部署文件,而後刷新頁面,就能看到咱們但願的效果啦:

項目總結

  1. 因爲以前的項目代碼都有,因此在重構的時候,基本上沒有花什麼時間就完成了項目的搭建,可以體會到代碼分離的重要性,這在很大程度上保證了咱們的代碼複用。
  2. 相較於以前用 Servlet + JSP 來完成,很明顯的感受是DAO層的編寫方便了不少,僅僅須要編寫一個 xml 映射文件和一個 Dao 層接口就能夠完成功能,而不用本身再去重複的去在每個 CRUD 方法中去處理結果集,重複並且繁瑣。
  3. 註解真的很方便,這不只僅提高了咱們自身開發的效率,寫起來也很帶勁兒。
  4. 開發效率快,並且低耦合,咱們基於 xml 配置了大部分的工做,在基於 SSM 框架開發時,咱們能夠把專一點集中在邏輯處理上。
  5. 在 SSM 框架中能方便的對項目進行修改,這不只僅得益於框架的約定,使得代碼分離而且可複用,也得益於 Maven 工具對於項目的管理。
  6. 咱們可以經過一個 Controller 來完成五個 Servlet 的功能,而且經過註解來完成配置。

項目改進

項目很簡單,僅僅也只是在數據庫增刪改查的基礎上增長了一個界面,咱們來動手改一改。

改進一:增長刪除提示

第一個想到的就是刪除提示,沒有刪除提示是很要命的一件事情,若是手滑了一下那可能就悲劇了....

首先咱們在頂部的 <head> 標籤中的 <script> 中增長一段代碼:

function del() {
    var msg = "您真的肯定要刪除嗎?\n\n請確認!";
    if (confirm(msg) == true) {
        return true;
    } else {
        return false;
    }
}

而後在刪除 a 標籤頁中增長 onclick 屬性:

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

當咱們刷新頁面後,點擊刪除就會彈出提示信息:

改進二:編輯頁面自動勾選上性別

在當前的項目中,若是點擊編輯按鈕進入到編輯頁面後,性別這個選項是空選的狀態,這就很low:

這個也很簡單,在 editStudent 頁面增長一些判斷就行了:

<c:if> 標籤來判斷 sex 的值,而後根據對應的屬性增長 checked 屬性,這樣就能夠自動勾選上所對應的屬性:

改進三:空值判斷

咱們容許設置爲 null 的值僅僅爲出生日期,其餘的值均不容許出現空值,因此咱們須要加入空值判斷:

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

而後再爲 form 建立一個 id 屬性值爲 「addForm」 並添加進判斷空值的方法:

  • 注意: 這裏須要寫在 $(function(){}) 裏面,等待文檔加載完畢才能生效。
  • 這裏並無爲 sex 屬性判斷空值,咱們採用一個簡單的爲 sex 添加一個默認勾選項來省略空值的判斷。

一樣的,咱們也在編輯頁面,採用一樣的方法進行空值判斷:

我有一個微信公衆號,常常會分享一些Java技術相關的乾貨;若是你喜歡個人分享,能夠用微信搜索「Java團長」或者「javatuanzhang」關注。

相關文章
相關標籤/搜索