SSM整合高級實例:學生管理系統(包含增刪改查和分頁功能)


🚩 整合說明

使用 Spring 去整合另外兩個框架,選擇XML + 註解的方式

👣 Outline

  • Spring 接管 service 層

  • Mybatis 接管 Dao 層 和 Bean 層

  • SpringMVC 接管 Controller 層

項目效果

項目包含學生信息的增刪改查功能以及分頁功能,最終效果如下圖所示:

項目源碼 + 目錄結構


一. 搭建Spring環境

1. 新建Maven的web工程

main 文件夾下建立 java 和 src 文件夾,並分別設置爲 Source root 和 Resources root

2. pom導入依賴

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!--版本鎖定-->
    <spring.version>5.0.2.RELEASE</spring.version> 
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>

    <!-- spring -->
    <dependency>
      <!--AOP-->
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <!--context容器-->
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <!--web相關-->
      <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>

    <dependency>
      <!--事務控制-->
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <!--jdbc模板技術-->
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

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

    <dependency>
      <!--mysql驅動-->
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <!--servlet-->
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <!--jsp-->
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <!--jstl-->
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- 日誌 -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- end -->

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


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

    <dependency>
      <!--連接池-->
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

  </dependencies>

3. 創建數據庫表

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

4. 編寫 Bean + Dao + Service

Bean (數據庫相關(Bean/Dao 都交給Mybatis管理))

public class Student {

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

    public Student() {
    }

    public Student(int id, int student_id, String name, int age, String sex, Date birthday) {
        this.id = id;
        this.student_id = student_id;
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getStudent_id() {
        return student_id;
    }

    public void setStudent_id(int student_id) {
        this.student_id = student_id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

}

Dao層無須實現接口,交給Mabatis來做

@Repository
public interface StudentDao {
    /**
     * 獲取學生總數
     * @return
     */
    int getTotal();

    /**
     * 添加一個學生
     * @param student
     */
    void addStudent(Student student);

    /**
     * 根據 id 刪除一個人學生
     * @param id
     */
    void deleteStudent(int id);

    /**
     * 修改一個學生信息
     * @param student
     */
    void updateStudent(Student student);

    /**
     * 根據 id 獲取一個學生信息
     * @param id
     * @return
     */
    Student getStudent(int id);

    /**
     * 查詢從start位置開始的count條數據
     */
    List<Student> list(int start, int count);
}

Service 需要實現接口(Service 層由 Spring 管理),在 Service 中注入 Dao 對象

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentDao studentDao;

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

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

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

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

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

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

Controller(交給 SpringMVC 管理)

@Controller
public class StudentController {
}

5. 編寫Spring配置文件

在resources文件夾下新建 spring-mybatis.xml 文件(我們將 mybatis 的配置也寫在該文件中,此處我們只列出 Spring 所需要的配置)

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

  <!-- Spring 接管 service, 掃描 service 包下所有使用註解的類型 -->
  <context:component-scan base-package="com.smallbeef.service"/>

二、搭建Spring+SpringMVC環境

1. web.xml 中配置前端控制器、過濾器、監聽Spring配置文件,並加載SpringMVC配置文件

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <!--解決中文亂碼的過濾器,一定要放在所有過濾器的前面-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <!--強制request編碼爲utf8-->
      <param-name>forceRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <!--強制response編碼爲utf8-->
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--配置spring的監聽器,
  該監聽器默認加載WEB-INF目錄下的applicationContext.xml的配置文件,所以我們需要自行配置路徑-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--配置加載路徑的配置文件-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>

  <!--配置前端控制器:服務器啓動加載,同時加載進springmvc的配置文件-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--配置初始化參數,加載springmvc的配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--服務器啓動的時候,讓DispatcherServlet對象創建-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--匹配所有請求-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
    
  <!--設置啓動頁爲 listStudent.jsp-->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/listStudent.jsp</url-pattern>
  </servlet-mapping>
  <!--設置啓動頁-->
  <welcome-file-list>
    <welcome-file>listStudent.jsp</welcome-file>
  </welcome-file-list>
</web-app>

SpringMVC 的默認啓動頁是 WEB-INF 文件夾下的 index.jsp 文件,此處我們修改默認啓動頁爲 resources 文件夾下的 listStudent.jsp 文件,需要在 web.xml 中添加配置:

 <!--設置啓動頁爲 listStudent.jsp-->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/listStudent.jsp</url-pattern>
  </servlet-mapping>
  <!--設置啓動頁-->
  <welcome-file-list>
    <welcome-file>listStudent.jsp</welcome-file>
  </welcome-file-list>

2. 編寫SpringMVC配置文件

在 resources 文件夾下新建 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
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- SpringMVC接管controller層,掃描web相關的bean -->
    <context:component-scan base-package="com.smallbeef.controller"/>

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

    <!--設置靜態資源不過濾-->
<!--    <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>-->
<!--    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>-->
<!--    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>-->

    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <!--jsp文件所在的目錄-->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <!--文件後綴名-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3. 編寫 Controller

在 Controller 中注入 Service 對象

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 增加一個學生信息
     * @param request
     * @param response
     * @return
     */
    @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";
    }

    /**
     * 根據 id 刪除一個學生信息
     * @param id
     * @return
     */
    @RequestMapping("/deleteStudent")
    public String deleteStudent(int id){
        studentService.deleteStudent(id);
        return "redirect:listStudent";
    }


    /**
     * 修改一個學生信息,進入修改界面editStudent後再調用
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/updateStudent")
    public String updateStudent(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.updateStudent(student);
        return "redirect:listStudent";
    }

    /**
     * 分頁顯示學生信息
     */
    @RequestMapping("/listStudent")
    public String listStudent(HttpServletRequest request, HttpServletResponse response) {

        // 獲取分頁參數
        int start = 0;
        int count = 6;

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

    /**
     * 用於修改學生信息界面的信息回顯
     * @param id
     * @return
     */
    @RequestMapping("/editStudent")
    public ModelAndView editStudent(int id){
        // 創建一個模型視圖對象
        ModelAndView mv = new ModelAndView();
        // 查詢學生信息
        Student student = studentService.getStudent(id);
        // 將數據放置到 ModelAndView 對象視圖中
        mv.addObject("student",student);
        // 放入 jsp 界面
        mv.setViewName("editStudent");
        return mv;
    }
}

4. 分頁模型 Page

在 util 包中 新建文件 Page.java

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

    public Page() {
    }

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

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = 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;
    }
}

4. 前端界面

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 --%>
    <!-- jQuery文件。務必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <title>學生管理頁面 - 首頁</title>
</head>

<body>
<div style="width:600px;height: 600px;position: absolute;left:50%;top:50%;margin-left:-300px;margin-top:-300px;">
    <h3 style="text-align: center">SSM整合實例 —— CRUD基本操作</h3>
    <div class="listDIV" >
        <table class="table table-striped table-bordered table-hover">
            <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" style="text-align: center;">
        <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" style="width: 300px;margin: 0 auto;">
        <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>
</div>
</body>
</html>

editStudent.jsp:修改學生信息界面

修改學生信息界面 和 增加學生信息 基本如出一轍,只不過修改學生界面多了信息回顯的功能。在 input 框中我們通過 EL 表達式進行信息回顯, 比如:

value="${student.age}"

我們在 controller 的方法 editStudent將通過 id 查詢到的 student 對象放入 ModelAndView 中,此處我們通過 EL 表達式取出其具體的值

詳細代碼如下:

<!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 --%>
    <!-- jQuery文件。務必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <title>學生管理頁面 - 編輯頁面</title>
</head>

<body>

<div class="editDIV" style="width:300px;margin:0 auto;">

    <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" value="${student.student_id}"></td>
                    </tr>
                    <tr>
                        <td>姓名:</td>
                        <td><input type="text" name="name" id="name" value="${student.name}"></td>
                    </tr>
                    <tr>
                        <td>年齡:</td>
                        <td><input type="text" name="age" id="age" value="${student.age}"></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">
                            <%--設置隱藏域,根據 id 進行發送數據--%>
                            <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>

三、搭建Spring+SpringMVC+Mybatis 環境

1. 編寫Mybatis全局配置文件

對於 Mybatis 的配置,我們將其與 Spring 的配置放在一個文件中:spring-mybatis.xml,Spring 接管 MyBatis 的 Session 工廠

<?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">
	
  <!-- Spring 配置 -->
  <!-- Spring接管service, 掃描service包下所有使用註解的類型 -->
  <context:component-scan base-package="com.smallbeef.service"/>

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

  <!-- 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}"/>
    <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"/>
    <!-- Mybaits接管bean層,掃描 bean包 使用別名 -->
    <property name="typeAliasesPackage" value="com.smallbeef.bean"/>
    <!-- 掃描sql配置文件:mapper需要的xml文件 -->
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
  </bean>

  <!-- Mybatis接管dao層, 配置掃描Dao接口包,動態實現Dao接口,注入到spring容器中 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 注入sqlSessionFactory -->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!-- 給出需要掃描Dao接口包 -->
    <property name="basePackage" value="com.smallbeef.dao"/>
  </bean>

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

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

2. 配置c3p0連接池

在 resources 文件夾下新建 jdbc.properties

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

📚 References

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章