科技政策查询功能(二)

功能实现:
1.主页面:

2.树状检索:勾选对应的显示对应的,都不勾选时显示所有

3.组合搜索:查询符合搜索字段的政策,可和树状检索功能共用

代码层

代码:

pojo类

package org.example.keji.pojo;

public class policy {

    private String id;
    private String name;//
    private String type;//
    private String category;
    private String range;
    private String document;
    private String organ;//
    private String viadata;
    private String pubdata;//
    private String perdata;

    public policy() {
    }

    public policy(String id, String name, String type, String category, String range, String document, String organ, String viadata, String pubdata, String perdata) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.category = category;
        this.range = range;
        this.document = document;
        this.organ = organ;
        this.viadata = viadata;
        this.pubdata = pubdata;
        this.perdata = perdata;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getRange() {
        return range;
    }

    public void setRange(String range) {
        this.range = range;
    }

    public String getDocument() {
        return document;
    }

    public void setDocument(String document) {
        this.document = document;
    }

    public String getOrgan() {
        return organ;
    }

    public void setOrgan(String organ) {
        this.organ = organ;
    }

    public String getViadata() {
        return viadata;
    }

    public void setViadata(String viadata) {
        this.viadata = viadata;
    }

    public String getPubdata() {
        return pubdata;
    }

    public void setPubdata(String pubdata) {
        this.pubdata = pubdata;
    }

    public String getPerdata() {
        return perdata;
    }

    public void setPerdata(String perdata) {
        this.perdata = perdata;
    }

    @Override
    public String toString() {
        return "policy{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", category='" + category + '\'' +
                ", range='" + range + '\'' +
                ", document='" + document + '\'' +
                ", organ='" + organ + '\'' +
                ", viadata='" + viadata + '\'' +
                ", pubdata='" + pubdata + '\'' +
                ", perdata='" + perdata + '\'' +
                '}';
    }
}

mapper:

package org.example.keji.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.example.keji.pojo.policy;

import java.util.List;

@org.apache.ibatis.annotations.Mapper
public interface Mapper {

    @Select("select * from policy")
    List<policy> select();

    @SelectProvider(type = PolicySqlProvider.class, method = "getSearchSql")
    List<policy> searchPolicies(@Param("name") String name,
                                @Param("organ") String organ,
                                @Param("type") String type,
                                @Param("document") String document);


}

动态sql类PolicySqlProvider

package org.example.keji.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;

public class PolicySqlProvider {
    public String getSearchSql(@Param("name") String name,
                               @Param("organ") String organ,
                               @Param("type") String type,
                               @Param("document") String document) {
        SQL sql = new SQL();
        sql.SELECT("*").FROM("policy");
        if (name != null && !name.isEmpty()) {
            sql.WHERE("name LIKE CONCAT('%', #{name}, '%')");
        }
        if (organ != null && !organ.isEmpty()) {
            sql.WHERE("organ LIKE CONCAT('%', #{organ}, '%')");
        }
        if (type != null && !type.isEmpty()) {
            sql.WHERE("type LIKE CONCAT('%', #{type}, '%')");
        }
        if (document != null && !document.isEmpty()) {
            sql.WHERE("document LIKE CONCAT('%', #{document}, '%')");
        }
        return sql.toString();
    }
}

service层

package org.example.keji.service;

import org.example.keji.mapper.Mapper;
import org.example.keji.pojo.policy;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@org.springframework.stereotype.Service
public class Service {
    @Autowired
    private Mapper mapper;
    public List<policy> Selectall(){
        List<policy> mess =mapper.select();
        return mess;
    }

    public List<policy> searchPolicies(String name, String organ, String type, String document) {
        return mapper.searchPolicies(name, organ, type, document);
    }



}

controller层

package org.example.keji.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.keji.pojo.policy;
import org.example.keji.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@org.springframework.stereotype.Controller
public class Controller {
    @Autowired
    private Service service;

    @GetMapping("/select")
    @ResponseBody
    public List<policy> select(HttpServletRequest req, HttpServletResponse resp)throws Exception {
        List<policy> mess=service.Selectall();
        return mess;
    }

    @PostMapping("/select")
    public void postSelect(HttpServletRequest req, HttpServletResponse resp)throws Exception {

    }

    @GetMapping("/search")
    @ResponseBody
    public List<policy> search(HttpServletRequest req) {
        System.out.println("1");
        String name = req.getParameter("name");
        String organ = req.getParameter("organ");
        String type = req.getParameter("type");
        String document = req.getParameter("document");
        System.out.println("Searching with name: " + name + ", organ: " + organ + ", type: " + type + ", document: " + document); // Debugging: Log the search parameters
        return service.searchPolicies(name, organ, type, document);
    }

    @PostMapping("/search")
    public void postSearch(HttpServletRequest req, HttpServletResponse resp)throws Exception {

    }
}



前端页面

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>科技政策查询</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      margin: 0;
      background-color: #f4f4f9;
    }

    h1 {
      text-align: center;
      margin: 20px 0;
      color: #333;
      font-size: 2.5rem;
    }

    #main-container {
      display: flex;
      flex: 1;
      margin: 0 20px 20px;
    }

    #tree {
      width: 250px;
      border-right: 1px solid #e0e0e0;
      padding: 15px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    #tree input[type="checkbox"] {
      margin-right: 8px;
    }

    #tree ul {
      list-style-type: none;
      padding: 0;
    }

    #tree li {
      margin-bottom: 8px;
    }

    #right-container {
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      margin-left: 20px;
    }

    #search-container {
      margin-bottom: 15px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }

    #search-container input[type="text"] {
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin-right: 10px;
      margin-bottom: 10px;
      width: calc(25% - 10px);
      box-sizing: border-box;
    }

    #search-container button {
      padding: 10px 20px;
      background-color: #007BFF;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    #search-container button:hover {
      background-color: #0056b3;
    }

    #result {
      flex-grow: 1;
      padding: 15px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      overflow-y: auto;
    }

    table {
      width: 100%;
      border-collapse: collapse;
    }

    th,
    td {
      border: 1px solid #e0e0e0;
      padding: 10px;
      text-align: left;
      max-width: 150px;
      word-wrap: break-word;
    }

    th {
      background-color: #f0f0f0;
    }

    tr:hover {
      background-color: #f0f0f0;
    }

    .pagination {
      margin-top: 20px;
      text-align: center;
    }

    .pagination button {
      padding: 8px 16px;
      background-color: #007BFF;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin: 0 5px;
      transition: background-color 0.3s ease;
    }

    .pagination button:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }

    .pagination button:hover:not(:disabled) {
      background-color: #0056b3;
    }
  </style>
</head>

<body>
<h1>科技政策查询系统</h1>
<div id="main-container">
  <div id="tree">
    <input type="checkbox" id="all" value="综合" onclick="filterPolicies()">
    <label for="all">综合</label>
    <ul>
      <li><input type="checkbox" value="科研机构改革" onclick="filterPolicies()">科研机构改革</li>
      <li><input type="checkbox" value="科技计划管理" onclick="filterPolicies()">科技计划管理</li>
      <li><input type="checkbox" value="科技经费与财务" onclick="filterPolicies()">科技经费管理</li>
      <li><input type="checkbox" value="基础研究与科研基地" onclick="filterPolicies()">基础研究与科研基地</li>
      <li><input type="checkbox" value="基础研究" onclick="filterPolicies()">基础研究</li>
      <li><input type="checkbox" value="科研基地" onclick="filterPolicies()">平台基地</li>
      <li><input type="checkbox" value="企业技术进步与高新技术产业化" onclick="filterPolicies()">企业技术进步与高新技术产业化</li>
      <li><input type="checkbox" value="企业" onclick="filterPolicies()">企业</li>
      <li><input type="checkbox" value="产业" onclick="filterPolicies()">产业</li>
      <li><input type="checkbox" value="创新载体" onclick="filterPolicies()">创新载体</li>
      <li><input type="checkbox" value="农村科技与社会发展" onclick="filterPolicies()">农村科技与社会发展</li>
      <li><input type="checkbox" value="科技人才" onclick="filterPolicies()">科技人才</li>
      <li><input type="checkbox" value="科技中介服务" onclick="filterPolicies()">科技中介服务</li>
      <li><input type="checkbox" value="科技条件与标准" onclick="filterPolicies()">科技条件与标准</li>
      <li><input type="checkbox" value="科技金融与税收" onclick="filterPolicies()">科技金融与税收</li>
      <li><input type="checkbox" value="科技成果与知识产权" onclick="filterPolicies()">科技成果与知识产权</li>
      <li><input type="checkbox" value="科技奖励" onclick="filterPolicies()">科技奖励</li>
      <li><input type="checkbox" value="科学技术普及" onclick="filterPolicies()">科学技术普及</li>
    </ul>
  </div>
  <div id="right-container">
    <div id="search-container">
      <input type="text" id="name" placeholder="政策标题">
      <input type="text" id="organ" placeholder="发文机构">
      <input type="text" id="type" placeholder="政策分类">
      <input type="text" id="document" placeholder="政策文号">
      <button onclick="searchPolicies()">查询</button>
    </div>
    <div id="result">
      <!-- Policies will be displayed here -->
    </div>
    <div class="pagination">
      <button onclick="prevPage()">上一页</button>
      <span id="currentPage">1</span>
      <button onclick="nextPage()">下一页</button>
    </div>
  </div>
</div>

<script>
  let currentPage = 1;
  const pageSize = 10;
  let allPolicies = [];
  let selectedTypes = [];

  function filterPolicies() {
    selectedTypes = Array.from(document.querySelectorAll('#tree input[type="checkbox"]:checked')).map(cb => cb.value);
    currentPage = 1;
    filterAndDisplayPolicies();
  }

  function searchPolicies() {
    const name = document.getElementById('name').value;
    const organ = document.getElementById('organ').value;
    const type = document.getElementById('type').value;
    const documentNum = document.getElementById('document').value;
    currentPage = 1;

    // 无论是否有参数,都向服务器发送请求
    const queries = { name, organ, type, document: documentNum };
    let url = '/search';
    const queryString = Object.entries(queries)
            .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
            .join('&');
    url += `?${queryString}`;

    console.log('发送请求到:', url);
    fetch(url)
            .then(response => response.json())
            .then(data => {
              allPolicies = data;
              filterAndDisplayPolicies();
            })
            .catch(error => {
              console.error('请求错误:', error);
              document.getElementById('result').innerHTML = '<p>查询数据失败,请检查网络或服务器</p>';
            });
  }

  function fetchAllPolicies() {
    const url = '/select';
    console.log('获取全部政策数据:', url);
    fetch(url)
            .then(response => response.json())
            .then(data => {
              allPolicies = data;
              filterAndDisplayPolicies();
            })
            .catch(error => {
              console.error('获取全部政策失败:', error);
              document.getElementById('result').innerHTML = '<p>初始化数据失败,请检查网络或服务器</p>';
            });
  }

  function filterAndDisplayPolicies() {
    let filteredPolicies = allPolicies;
    if (selectedTypes.length > 0) {
      filteredPolicies = allPolicies.filter(policy => selectedTypes.includes(policy.type));
    }
    displayPolicies(filteredPolicies);
  }

  function displayPolicies(policies) {
    const resultDiv = document.getElementById('result');
    resultDiv.innerHTML = '';
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    const pagePolicies = policies.slice(start, end);

    const table = document.createElement('table');
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    const headers = ['政策标题', '发文机构', '政策分类', '发文日期'];
    headers.forEach(headerText => {
      const th = document.createElement('th');
      th.textContent = headerText;
      headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    table.appendChild(thead);

    const tbody = document.createElement('tbody');
    pagePolicies.forEach(policy => {
      const row = document.createElement('tr');
      const cells = [
        policy.name || '未标注',
        policy.organ || '未标注',
        policy.type || '未标注',
        policy.perdata || '未标注'
      ];
      cells.forEach(cellText => {
        const td = document.createElement('td');
        td.textContent = cellText;
        row.appendChild(td);
      });
      tbody.appendChild(row);
    });
    table.appendChild(tbody);

    resultDiv.appendChild(table);
    updatePagination(policies.length);
  }

  function updatePagination(totalPolicies) {
    const pageCount = Math.ceil(totalPolicies / pageSize);
    document.getElementById('currentPage').textContent = currentPage;
    if (currentPage === 1) {
      document.querySelector('button[onclick="prevPage()"]').disabled = true;
    } else {
      document.querySelector('button[onclick="prevPage()"]').disabled = false;
    }
    if (currentPage === pageCount) {
      document.querySelector('button[onclick="nextPage()"]').disabled = true;
    } else {
      document.querySelector('button[onclick="nextPage()"]').disabled = false;
    }
  }

  function prevPage() {
    if (currentPage > 1) {
      currentPage--;
      filterAndDisplayPolicies();
    }
  }

  function nextPage() {
    const pageCount = Math.ceil(allPolicies.length / pageSize);
    if (currentPage < pageCount) {
      currentPage++;
      filterAndDisplayPolicies();
    }
  }

  // Initial fetch of all policies
  fetchAllPolicies();
</script>
</body>

</html>    
posted @ 2025-04-03 08:45  茆伟昊  阅读(22)  评论(0)    收藏  举报