1. 程式人生 > 實用技巧 >Spring mvc 實現新聞查詢,分類查詢

Spring mvc 實現新聞查詢,分類查詢

一:分頁

匯入包

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
<!--1)spring 以及spring mvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.14.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.14.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.14.RELEASE</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.0.14.RELEASE</version>
    </dependency>
<!--2)mysql驅動-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.48</version>
    </dependency>
<!--  3)  mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.4</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>

<!-- 4) servlet   -->
    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <scope>provided</scope>
      <version>2.0</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

<!--    5) mbg-->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.4.0</version>
    </dependency>


<!--    6)log4j-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.12</version>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>

  在beans-datasoure.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:aop="http://www.springframework.org/schema/aop"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
         http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        ">
	<!--1、載入資料庫的配置資訊 -->
	<context:property-placeholder
		location="classpath:jdbc.properties" />
	<!--2、datasource資料來源 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${uName}" />
		<property name="password" value="${password}" />
	</bean>
	<!-- 3、sqlSessionFactory -->
	<!-- 3、sqlSessionFactory -->
	<bean id="sqlSessionFactory"
		  class="org.mybatis.spring.SqlSessionFactoryBean">
		<!--分頁-->

		<!-- 別名 -->
		<property name="typeAliasesPackage"  value="cc.entity"></property>

		<!-- mapper  XML對映 -->
		<property name="mapperLocations"  value="classpath*:cc.mapper/*Mapper.xml"></property>

		<!-- 資料來源 -->
		<property name="dataSource" ref="dataSource"></property>

		<property name="plugins">
			<array>
				<bean class="com.github.pagehelper.PageInterceptor">
					<!-- 這裡的幾個配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->
					<property name="properties">
						<value>
							helperDialect=mysql
							reasonable=true
							supportMethodsArguments=true
							params=count=countSql
							autoRuntimeDialect=true
						</value>

					</property>

				</bean>
			</array>
		</property>

	</bean>

	<!--4、mapper介面的位置 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="cc.mapper"></property>
	</bean>
</beans>

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


	<!-- 1、註解掃描 -->
	<!-- 2、datasource:mybatis -->
	<import resource="beans-datasource.xml"/>

</beans>

  加入spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
	<!-- 開啟註解掃描  .** 所有所有包以及子包-->
	<context:component-scan base-package="cc.**"/>

	<!-- 1.處理器對映器 -->
	<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
	<!-- 2.處理器介面卡 -->
	<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
	<!-- 3.試圖解析器 -->
	<mvc:annotation-driven/>
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 解析jstl標籤 -->
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<!-- 動態頁面的字首 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 動態頁面的字尾 -->
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

  使用generator.xml生成mapper和實體類

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/t142" userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
            userId="yycg"
            password="yycg">
        </jdbcConnection> -->

        <!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把JDBC DECIMAL 和
            NUMERIC 型別解析為java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO類的位置 -->
        <javaModelGenerator targetPackage="pojo"
                            targetProject=".\src">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
            <!-- 從資料庫返回的值被清理前後的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper對映檔案生成的位置 -->
        <sqlMapGenerator targetPackage="cc.mapper"
                         targetProject=".\src">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper介面生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="cc.mapper"
                             targetProject=".\src">
            <!-- enableSubPackages:是否讓schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
         <!--指定資料庫表-->
        <table tableName="edoc_category"
               domainObjectName="Edoc_category"
               enableCountByExample="true"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               enableUpdateByExample="false"></table>

        <table tableName="edoc_entry"
               domainObjectName="Edoc_entry"
               enableCountByExample="true"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               enableUpdateByExample="false"></table>

        <!--<table tableName="test" domainObjectName="Test" enableCountByExample="false" enableDeleteByExample="false"-->
        <!--enableSelectByExample="false" enableUpdateByExample="false"></table>-->

    </context>
</generatorConfiguration>

  建立service和實現類

package cc.service;

import cc.entity.Edoc_entry;

import java.util.List;

public interface Edoc_entryService {

    /**
     *
     * @Title: list 
     * @Description: 獲取所有使用者的所有資訊
     * @param @return
     * @return List<Users>
     * @throws
     */
    List<Edoc_entry> list();

    Edoc_entry selectById(int id);

    int update(Edoc_entry edoc_entry);
    /*
    * 新增使用者
    * */
    int save(Edoc_entry edoc_entry);

    /*
* 刪除資料
* */
    int delete(int id);


    List<Edoc_entry> findEntryByCate(int cateId);
}

  

package cc.service;

import cc.entity.Edoc_category;

import java.util.List;

public interface Edoc_categoryService {

    List<Edoc_category> list();

}

  

package cc.service.impl;

import cc.entity.Edoc_categoryExample;
import cc.entity.Edoc_entry;
import cc.entity.Edoc_entryExample;
import cc.mapper.Edoc_entryMapper;
import cc.service.Edoc_entryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Edoc_entryServiceImpl implements Edoc_entryService {

    @Autowired
    private Edoc_entryMapper edoc_entryMapper;

    @Override
    public List<Edoc_entry> list() {
        return edoc_entryMapper.selectByExample(null);
    }

    @Override
    public Edoc_entry selectById(int id) {
        return edoc_entryMapper.selectByPrimaryKey(id);
    }

    @Override
    public int update(Edoc_entry edoc_entry) {
        return edoc_entryMapper.updateByPrimaryKey(edoc_entry);
    }

    @Override
    public int save(Edoc_entry edoc_entry) {
        return edoc_entryMapper.insert(edoc_entry);
    }

    @Override
    public int delete(int id) {
        return edoc_entryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Edoc_entry> findEntryByCate(int cateId) {
        //1.構建Example
        Edoc_entryExample example = new Edoc_entryExample();
        //2.根據example構建criteria(條件物件)
        Edoc_entryExample.Criteria criteria = example.createCriteria();
        //3.設定條件 :categoryId=3
        criteria.andCategoryidEqualTo(cateId);

        return edoc_entryMapper.selectByExample(example);
    }
}

  

package cc.service.impl;

import cc.entity.Edoc_category;
import cc.mapper.Edoc_categoryMapper;
import cc.service.Edoc_categoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class Edoc_categoryServiceImpl implements Edoc_categoryService{

    @Autowired
    private Edoc_categoryMapper edoc_categoryMapper;

    @Override
    public List<Edoc_category> list() {
        return edoc_categoryMapper.selectByExample(null);
    }
}

  Mapper檔案中,加入查詢集合的方法

package cc.mapper;

import cc.entity.Edoc_entry;
import cc.entity.Edoc_entryExample;

import java.util.List;

public interface Edoc_entryMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Edoc_entry record);

    int insertSelective(Edoc_entry record);

    Edoc_entry selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Edoc_entry record);

    int updateByPrimaryKey(Edoc_entry record);

    List<Edoc_entry> selectByExample(Edoc_entryExample example);
}

  

package cc.mapper;


import cc.entity.Edoc_category;
import cc.entity.Edoc_categoryExample;

import java.util.List;

public interface Edoc_categoryMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Edoc_category record);

    int insertSelective(Edoc_category record);

    Edoc_category selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Edoc_category record);

    int updateByPrimaryKey(Edoc_category record);

    List<Edoc_category> selectByExample(Edoc_categoryExample example);
}

  並修改mapper.xml

<select id="selectByExample" parameterType="cc.entity.Edoc_entryExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from edoc_entry
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>

  

<select id="selectByExample" parameterType="cc.entity.Edoc_categoryExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from edoc_category
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>

  寫入Controller

package cc.web;


import cc.entity.Edoc_category;
import cc.entity.Edoc_entry;
import cc.service.Edoc_categoryService;
import cc.service.Edoc_entryService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/edoc_entry")
public class Edoc_entryController {

    @Autowired
    private Edoc_entryService edoc_entryService;

    @Autowired
    private Edoc_categoryService edoc_categoryService;

    @ModelAttribute(value = "categories")
    public List<Edoc_category> getCategories(){
        List<Edoc_category> categories = edoc_categoryService.list();
        return categories;
    }

    @RequestMapping(value = "/list")
    public ModelAndView list() {

        //    public ModelAndView list() {
        ModelAndView mv = new ModelAndView();
        //1.呼叫使用者的service層的方法獲取所有使用者所有資料
        List<Edoc_entry> edoc_entries = edoc_entryService.list();

        //2.將資料繫結mv上
        mv.addObject("edoc_entries", edoc_entries);

        //3.設定檢視
        mv.setViewName("edoc_entry/list");
        //4.放回mv
        return mv;
    }

    @RequestMapping("/to_edit")
    public ModelAndView toUpdate(int id) {
        System.out.println("====進入toUpdate===id=>" + id);
        ModelAndView mv = new ModelAndView();
        //1.查詢該使用者的所有資訊  web--servcice-maper-資料
        Edoc_entry edoc_entry = edoc_entryService.selectById(id);
        //2.將該使用者資料繫結到mv
        mv.addObject("edoc_entry", edoc_entry);
        //3.將修改頁面的jsp名稱繫結到mv中
        mv.setViewName("edoc_entry/edit");
        //4.返回mv
        return mv;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ModelAndView update(Edoc_entry edoc_entry) {
        System.out.println("====進入update===user=" + edoc_entry);
        ModelAndView mv = new ModelAndView();
        //1.呼叫service更新使用者資訊
        int result = edoc_entryService.update(edoc_entry);
        //2.繫結檢視
        if (result > 0) {//更新成功
            //重定向 ,edoc_entry/list的對映的list()方法,再由list()跳轉到edoc_entry/list.jsp
            mv.setViewName("redirect:../edoc_entry/list");
        } else {//更新失敗

        }
        //3.返回mv
        return mv;
    }

    @RequestMapping("/to_add")
    public String toAdd() {

        return "edoc_entry/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Edoc_entry edoc_entry) {
        System.out.println("====進入add===edoc_entry=" + edoc_entry);
        //1.呼叫service新增使用者資訊方法
        int result = edoc_entryService.save(edoc_entry);
        //2.繫結檢視
        if (result > 0) {//更新成功
            //重定向 ,edoc_entry/list的對映的list()方法,再由list()跳轉到edoc_entry/list.jsp
            return "redirect:../edoc_entry/list";
        } else {//更新失敗
            return "error";
        }
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam("tid") int tid) {
        System.out.println("====進入delete===userId=" + tid);
        //1.呼叫service新增使用者資訊方法
        int result = edoc_entryService.delete(tid);
        //2.繫結檢視
        if (result > 0) {//更新成功
            //重定向 ,user/list的對映的list()方法,再由list()跳轉到user/list.jsp
            return "redirect:../edoc_entry/list";
        } else {//更新失敗
            return "error";
        }
    }

    //根據分類id獲取對應的所有電子文件
    @RequestMapping("/entrys")
    public String entrysByCate(Model model , int cateId){
        //1.呼叫service獲取該分類的電子文件
        List<Edoc_entry> edoc_entries = edoc_entryService.findEntryByCate(cateId);
        //2.繫結到model
        model.addAttribute("edoc_entries",edoc_entries);
        //3.跳轉到頁面
        return "edoc_entry/template";

    }

}

  最後將jsp頁面寫好

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/edoc_entry/add" method="post">
    <table border="1" align="center" width="50%" height="100px">
        <tr>
            <th>文件型別</th>
            <th>文件名稱</th>
            <th>文件摘要</th>
            <th>上傳人</th>
            <th>上傳人時間</th>
        </tr>
        <tr align="center">

        <tr align="center">
            <td><div style="width:400px;margin: 0px auto;">

                <p>
                    <select name="categoryid">
                        <c:forEach items="${categories}" var="categories1">
                            <option value="${categories1.id}">${categories1.name}</option>
                        </c:forEach>
                    </select>
                </p>
            </div></td>
            <td><input type="text" name="title"/> </td>
            <td><input type="text" name="summary"/> </td>
            <td><input type="text" name="uploaduser"/> </td>
            <td>
                <!-- html5 中新增的標籤:日期標籤 -->
                <input type="date" name="createdate"
                       value="<fmt:formatDate value='' pattern='yyyy-MM-dd'/>"/>
            </td>
        </tr>
        </tr>
        <tr>
            <td colspan="4" align="center">
                <input type="submit" value="增加"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jstl/fmt_rt"  prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <form action="${pageContext.request.contextPath}/edoc_entry/update" method="post">
    <table border="1" align="center" width="50%"  height="100px">
        <tr>
            <th>文件編號</th>
            <th>文件名稱</th>
            <th>文件摘要</th>
            <th>上傳人</th>
            <th>上傳人時間</th>
        </tr>
            <tr align="center">
                <td><input value="${edoc_entry.id}" name="id" readonly="readonly"/></td>
                 <td><input type="text" name="title" value="${edoc_entry.title }"/> </td>
                 <td><input type="text" name="summary" value="${edoc_entry.summary }"/> </td>
                 <td><input type="text" name="uploaduser" value="${edoc_entry.uploaduser }"/> </td>
                <td>
                    <!-- html5 中新增的標籤:日期標籤 -->
                    <input type="date" name="createdate"
                    value="<fmt:formatDate value='${edoc_entry.createdate}' pattern='yyyy-MM-dd'/>"/>
                </td>
            </tr>
            <tr>
              <td colspan="5" align="center">
                    <input type="submit" value="更新"/>
                </td>
            </tr>
    </table>
    </form>
</body>
</html>

  

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/12/23 0023
  Time: 11:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<html>
<head>
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

    <script type="text/javascript">

        $(function(){
            $("#searchBtn").click(function(){
                // alert(1);
                //1.獲取使用者選擇的分類
                var cateId = $("#name1").val();
                //2.根據id獲取所有分類電子文件
                $.ajax({
                    type: "GET",
                    url: "http://localhost:8080/edoc_entry/entrys",
                    data: "cateId="+cateId,
                    success: function(bookList){
                        //alert( "Data Saved: " + bookList );
                        $("#book_list").html(bookList);
                    }
                });

            });
        })

    </script>

</head>
<body>
<div style="width:400px;margin: 0px auto;">

    <p>文件分類
        <select id="name1">
            <c:forEach items="${categories}" var="categories1">
                <option value="${categories1.id}">${categories1.name}</option>
            </c:forEach>
        </select>
        <button id="searchBtn">查詢</button>
    </p>
</div>

<%--<form action="${pageContext.request. contextPath}/user/delBatch">--%>
<table width="80%" border="1">
    <thead>
    <tr>
        <%--<th><input type="checkbox" id="totalCheck" /> </th>--%>
        <th>文件編號</th>
        <th>文件名稱</th>
        <th>文件摘要</th>
        <th>上傳人</th>
        <th>上傳人時間</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="book_list">
    <c:forEach items="${edoc_entries}" var="entries">
        <tr>
            <th>${entries.id}</th>
            <th>${entries.title}</th>
            <th>${entries.summary }</th>
            <th>${entries.uploaduser}</th>
            <th><fmt:formatDate value='${entries.createdate}' pattern='yyyy-MM-dd'/></th>
            <th>
                <a href="${pageContext.request. contextPath}/edoc_entry/to_edit?id=${entries.id}">修改</a>

                <a href="${pageContext.request. contextPath}/edoc_entry/to_add">增加</a>

                <a href="javascript:doDel('http://localhost:8080/edoc_entry/delete?tid=${entries.id}')">刪除</a>

                    <%--<a href="javascript:remove('http://localhost:8080/user/delete/${user.id}')">刪除(rest)</a>--%>
            </th>
        </tr>
    </c:forEach>
    </tbody>
</table>
<%--</form>--%>
<script type="text/javascript">

    function doDel(url) {

        if (confirm("確定刪除嗎?")) {

            location.href = url;

        }
    }


</script>

</body>
</html>

  

<%--
  Created by IntelliJ IDEA.
  User: mr.chan
  Date: 2020-12-24
  Time: 14:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<html>
<head>
    <title>非同步載入模板</title>
</head>
<body>

<c:forEach items="${edoc_entries}" var="entries">
    <tr>
        <th>${entries.id}</th>
        <th>${entries.title}</th>
        <th>${entries.summary }</th>
        <th>${entries.uploaduser}</th>
        <th><fmt:formatDate value='${entries.createdate}' pattern='yyyy-MM-dd'/></th>
        <th>
            <a href="${pageContext.request. contextPath}/edoc_entry/to_edit?id=${entries.id}">修改</a>

            <a href="${pageContext.request. contextPath}/edoc_entry/to_add">增加</a>

            <a href="javascript:doDel('http://localhost:8080/edoc_entry/delete?tid=${entries.id}')">刪除</a>

                <%--<a href="javascript:remove('http://localhost:8080/user/delete/${user.id}')">刪除(rest)</a>--%>
        </th>
    </tr>
</c:forEach>

</body>
</html>

  

注意:web.xml檔案是最開始就執行的,所以要記得寫

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <!--一、spring的ioc容器配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 三、spring的編碼過濾器 -->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 二、中央處理器(DispatcherServlet):對映器、介面卡、檢視解析器 -->
  <servlet>
    <servlet-name>app</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>app</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

</web-app>

  還要,實體類裡面有Date型別的要加入註釋

 @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date createdate;

  並加入DateHandlerMethodArgumentResolver和MyDate介面

package cc.annotation;

import java.lang.annotation.*;

//該註解只能在哪裡使用  (方法引數上)  
//Type註解只能使用在類上  
//Method註解只能能用方法上
//PARAMETER 只能用在方法引數上
@Target(ElementType.PARAMETER)
//執行策略 (一般RUNTIME)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyDate {

    String[] params() default ""; /*從網頁中獲取到的日期繫結哪個引數屬性上*/

    String pattern() default "yyyy-MM-dd HH:mm:ss";/*預設的日期格式*/

}

  

package cc.annotation.support;

import cc.annotation.MyDate;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;


/**
 *  jsp(表單---string)==========>servlet(request.getParameter()--手動將jsp獲取的string實體類中屬性引數型別)
    * @ClassName: DateHandlerMethodArgumentResolver 
 * @Description: TODO 
 * @author 新夢想IT學院.陳超
 * @date 2020年12月22日 
 *  
 */
public class DateHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    private String[] params;  /*屬性*/
    private String pattern;   /*日期的格式*/

    /**
     * MethodParameter:controller的方法引數物件
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //1、判斷controller方法上是否有MyDate註解
        boolean hasParameterAnnotation = parameter.hasParameterAnnotation(MyDate.class);
        if (!hasParameterAnnotation) {
            //不會進入下面的resolveArgument方法進行引數的解析
            return false;
        }
        //2、獲取Date註解物件
        MyDate parameterAnnotations = parameter.getParameterAnnotation(MyDate.class);
        //3、獲取Date註解的params引數
        String[] parameters = parameterAnnotations.params();
        if (!StringUtils.isEmpty(parameters)) {
            params = parameters;
            //4.獲取Date註解的pattern引數
            pattern = parameterAnnotations.pattern();
          //進入下面的resolveArgument方法進行引數的解析
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParam, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //1.獲取controller方法引數Users user的型別物件
        Object object = BeanUtils.instantiateClass(methodParam.getParameterType());
        //2.獲取引數型別物件的類資訊(Users類的屬性和方法)
        BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
        //3.獲取請求物件Request
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
         //4.獲取Users類型別物件的所有屬性描述(獲取Users類的所有屬性)
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            //5.得到每個屬性的名字(Users類的屬性名),並根據屬性名稱得到請求引數的值
            String value = request.getParameter(propertyDescriptor.getName());
            //6.判斷非空
            if (!StringUtils.isEmpty(value)) {
                //5.得到屬性的set方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                //6.如果set方法為非公有方法,暴力破解
                if (!Modifier.isPublic(writeMethod.getModifiers())) {
                    writeMethod.setAccessible(true);
                }
                //7.判斷屬性名是否為Date指定的params值,如果是params指定值 則進行日期轉換
                if (propertyDescriptor.getName().equals(params[0])) {//日期屬性
                    SimpleDateFormat sdf = new SimpleDateFormat(this.pattern);
                    java.util.Date date = sdf.parse(value);
                    //呼叫setBirthday(date)
                    writeMethod.invoke(object, date);
                } else {//非日期的屬性
                    //屬性型別為Integer
                    if(propertyDescriptor.getPropertyType().equals(Integer.class)) {
                        writeMethod.invoke(object, Integer.parseInt(value));
                     //屬性型別為字串
                    }else {
                        writeMethod.invoke(object, value);
                    }
                }
            }
        }
        return object;
    }
}