Java Web简单搜索功能实现

Java Web 专栏收录该内容
0 篇文章 0 订阅

小demo,没有使用框架。

 

 

webapp项目,用到了servlet + jsp,使用jdbc从MySQL中查询数据

构建工具maven

 

先上截图

pom.xml 注意版本问题!

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <log4j-core.version>2.8.2</log4j-core.version>
    <junit.version>4.11</junit.version>
    <servlet.version>3.0.1</servlet.version>
    <jsp.version>2.1</jsp.version>
    <jstl.version>1.2</jstl.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <!--log4j日志-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j-core.version}</version>
    </dependency>

    <!-- mysql 8-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
    </dependency>

    <!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
  </dependencies>

index.jsp 前端页面

<%@ page isELIgnored="false" %>
<%@ page language="java" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <style>
        #keyword {
            background-image: url('https://static.runoob.com/images/mix/searchicon.png'); /* 搜索按钮 */
            background-position: 10px 12px; /* 定位搜索按钮 */
            background-repeat: no-repeat; /* 不重复图片 */
            width: 100%;
            font-size: 16px;
            padding: 12px 20px 12px 40px;
            border: 1px solid #ddd;
            margin-bottom: 12px;
        }

        #myTable {
            border-collapse: collapse;
            width: 100%;
            border: 1px solid #ddd;
            font-size: 18px;
        }

        #myTable th, #myTable td {
            text-align: left;
            padding: 12px;
        }

        #myTable tr {
            /* 表格添加边框 */
            border-bottom: 1px solid #ddd;
        }

        #myTable tr.header, #myTable tr:hover {
            /* 表头及鼠标移动过 tr 时添加背景 */
            background-color: #f1f1f1;
        }
    </style>
    <script>
        // onclick事件
        function search() {
            // var $keyword = $("#keyword").val();
            var $keyword = document.getElementById("keyword").value;
            // todo 发起请求
            window.location.href = "/query?param=" + $keyword;
        }

        // 按Enter键,执行事件
        function entersearch() {
            var event = window.event || arguments.callee.caller.arguments[0];
            if (event.keyCode == 13) {
                search();
            }
        }
    </script>
</head>
<body>

<div style="margin: 20px 122px">
    <%--<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search">--%>
    <input type="text" name="keyword" id="keyword" placeholder="Search" onkeydown="entersearch()"/>

    <table id="myTable">
        <tr class="header">
            <th style="width:15%;">phone</th>
            <th style="width:15%;">start_time</th>
            <th style="width:15%;">end_time</th>
            <th style="width:15%;">host</th>
            <th style="width:15%;">rule</th>
            <th style="width:15%;">type</th>
        </tr>
        <c:forEach items="${list}" var="u" varStatus="vs">
            <tr>
                <td>${u.id}</td>
                <td>${u.startTime}</td>
                <td>${u.endTime}</td>
                <td>${u.hostss}</td>
                <td>${u.rule}</td>
                <td>${u.type}</td>
            </tr>
        </c:forEach>
    </table>
</div>

</body>
</html>

ResultServlet.java  servlet

package com.dinary.controller;

import com.dinary.pojo.Datax;
import com.dinary.util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author dcy
 * @create 2019-07-23 上午9:41
 */
@WebServlet(name = "ResultServlet", urlPatterns = "/query")
public class ResultServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("param");
        List<Datax> res = null;
        try {
            if ("".equals(param) && param.length() == 0) {
                res = JDBCUtil.queryAll();
            } else {
                res = JDBCUtil.query(param);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("list", res);
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Datax.java 返回数据

package com.dinary.pojo;

/**
 * 返回给前端数据
 */
public class Datax {

  private String id;
  private String startTime;
  private String endTime;
  private String hostss;
  private String rule;
  private String type;


  public String getId() {
    return id;
  }

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


  public String getStartTime() {
    return startTime;
  }

  public void setStartTime(String startTime) {
    this.startTime = startTime;
  }


  public String getEndTime() {
    return endTime;
  }

  public void setEndTime(String endTime) {
    this.endTime = endTime;
  }


  public String getHostss() {
    return hostss;
  }

  public void setHostss(String hostss) {
    this.hostss = hostss;
  }


  public String getRule() {
    return rule;
  }

  public void setRule(String rule) {
    this.rule = rule;
  }


  public String getType() {
    return type;
  }

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

}

JDBCUtil.java 数据库工具类

package com.dinary.util;

import com.dinary.pojo.Datax;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author dcy
 * @create 2019-07-23 上午7:48
 */
public class JDBCUtil {
    /**
     *  mysql 8 :com.mysql.cj.jdbc.Driver
     */
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/dinary";
    static final String USER = "root";
    static final String PASS = "123456";

    static Connection conn;
    static PreparedStatement ps;

    static {
        // 注册 JDBC 驱动
        try {
            Class.forName(JDBC_DRIVER);
            // 打开链接
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<Datax> query(String param) throws Exception{
        String sql = "select * from datax where id = ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, param);
        ResultSet rs = ps.executeQuery();
        List<Datax> list  = new ArrayList<>();
        while (rs.next()) {
            Datax s = new Datax();
            s.setId(rs.getString(1));
            s.setStartTime(rs.getString(2));
            s.setEndTime(rs.getString(3));
            s.setHostss(rs.getString(4));
            s.setRule(rs.getString(5));
            s.setType(rs.getString(6));
            list.add(s);
        }
        return list;
    }

    public static List<Datax> queryAll() throws Exception{
        String sql = "select * from datax";
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        List<Datax> list  = new ArrayList<>();
        while (rs.next()) {
            Datax s = new Datax();
            s.setId(rs.getString(1));
            s.setStartTime(rs.getString(2));
            s.setEndTime(rs.getString(3));
            s.setHostss(rs.getString(4));
            s.setRule(rs.getString(5));
            s.setType(rs.getString(6));
            list.add(s);
        }
        return list;
    }


    public static void close() throws Exception{
        if (conn != null) {
            conn.close();
        }
        if (ps != null) {
            ps.close();
        }
    }
}

一个简单的搜索功能就完成了

 

评论 1 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页

打赏作者

薛定谔的空气

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值