功能介绍:

  1. 用户可以通过前台异步查询数据
  2. 用户可以根据题中的部分字段对数据库中相匹配的数据进行查询,并返回给前台
  3. 主要功能实现题库的简单查询

实现环境

  • 前端:html + css + js
  • 后端:java + servlet + mysql + tomcat + json

静态资源:

Ajax代码实现:

<script>
    $(function(){
        //按钮点击事件
        $('#getWk').click(function(){
            let topic = $("#topic").val();

            //使用ajax处理请求和响应
            $.ajax({
                type: "get",
                url: "search",
                data: {topic:topic},
                dataType: "json",
                success: function(result){

                    if (result == false){
                        alert("输入的信息不合法,请重新输入! ! !");
                    }

                    let request = "<tr>\n" +
                            "        <th>序号</th>\n" +
                            "        <th>题目</th>\n" +
                            "        <th>选项</th>\n" +
                            "        <th>答案</th>\n" +
                            "    </tr><hr>";
                    //遍历servlet中返回的结果
                    $.each(result,function (index, element) {

                        let i = 1;
                        request += '<tr><th >' + element.id + '</th>'
                        + '<th >' + element.title + '</th>'
                        + '<th >' + element.choose + '</th>'
                        + '<th >' + element.answer + '</th> </tr><hr>';
                    });
                    //将生成的html展示在页面中
                    $('#request').html(request);
                },
                error:function(){
                    alert("请正确输入信息后,再进行查询!!");
                }
            });
        });
    });
</script>

servlet代码实现:

@javax.servlet.annotation.WebServlet("/search")
public class SearchServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    //获取前台传入参数
    String topic = request.getParameter("topic");

    //判断用户输入的是否为空
    //如果为空则直接返回,由前台做出提示
    if (topic.equals("")){
        return;
    }

    //处理数据
    SearchDaoImpl searchDao = new SearchDaoImpl();
    List<Topic> list = searchDao.findTopic(topic);

    //返回数据
    //将info对象序列化json
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(list);

    //将json数据写回客户端
    //设置content-type
    response.setContentType("application/json;charset=utf-8");
    response.getWriter().write(json);

}

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    this.doPost(request,response);
}
}

业务实现:

public interface SearchDao {
    List<Topic> findTopic(String topic);
}
public class SearchDaoImpl implements SearchDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public List<Topic> findTopic(String topic) {
    
    //规定一次最多展示15条语句
    int size = 15;
    topic = "%" + topic + "%";
    String sql = "SELECT * FROM tk_new WHERE title LIKE ? OR choose LIKE ? LIMIT ?";
    List<Topic> topic1 =  template.query(sql, new BeanPropertyRowMapper<>(Topic.class), topic,topic,size);
    return topic1;
}
}

实体类:

/**
 * 题库实体类
 */

public class Topic  {
private Integer id;

private String title;

private String choose;

private String answer;

@Override
public String toString() {
    return "Topic{" +
            "id=" + id +
            ", title='" + title + '\'' +
            ", choose='" + choose + '\'' +
            ", answer='" + answer + '\'' +
            '}';
}

public Integer getId() {
    return id;
}

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

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getChoose() {
    return choose;
}

public void setChoose(String choose) {
    this.choose = choose;
}

public String getAnswer() {
    return answer;
}

public void setAnswer(String answer) {
    this.answer = answer;
}
}

JDBCutils实现;

/*
1. 声明静态数据源成员变量
2. 创建连接池对象
3. 定义公有的得到数据源的方法
4. 定义得到连接对象的方法
5. 定义关闭资源的方法
 */
public class JDBCUtils {
// 1.    声明静态数据源成员变量
private static DataSource ds;

// 2. 创建连接池对象
static {
    // 加载配置文件中的数据
    InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("/mysql.properties");
    Properties pp = new Properties();
    try {
        pp.load(is);
        // 创建连接池,使用配置文件中的参数
        ds = DruidDataSourceFactory.createDataSource(pp);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

// 3. 定义公有的得到数据源的方法
public static DataSource getDataSource() {
    return ds;
}

// 4. 定义得到连接对象的方法
public static Connection getConnection() throws SQLException {
    return ds.getConnection();
}

// 5.定义关闭资源的方法
public static void close(Connection conn, Statement stmt, ResultSet rs) {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {}
    }

    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException e) {}
    }

    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {}
    }
}

// 6.重载关闭方法
public static void close(Connection conn, Statement stmt) {
    close(conn, stmt, null);
}
}

mysql配置文件:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=wuquejs99
initialSize=5
maxActive=10
maxWait=3000

依赖:

<dependencies>
<!--mysql驱动-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.26</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>4.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>4.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>4.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>4.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  <version>1.1.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.0.9</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>compile</scope>
</dependency>
</dependencies>

项目打包:

奈何本人才疏学浅,如有错误之处,望大佬指正!!!

最后修改:2020 年 11 月 11 日 02 : 57 PM