個人筆記之json實現模糊查詢


1:首先創建一個項目如:(說明:此項目是在eclipse創建的)

2.在創建相對應的包如:

 

3.創建寫好相對應的配置文件如:

applicationContext.xml具體內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
">
<!--自動注入processor解釋器(此行不寫)-->
<context:annotation-config></context:annotation-config>
<!--自動掃描包-->
<context:component-scan base-package="com.nf"></context:component-scan>

<!--加載JDBC的配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<!--幾個個性化的信息-->
<!--每300秒檢查所有連接池中空閑的連接-->
<property name="idleConnectionTestPeriod" value="300"></property>
<!--最大的空閑時間-->
<property name="maxIdleTime" value="2000"></property>
<!--最大連接數-->
<property name="maxPoolSize" value="5"></property>
</bean>

<!--構造SessionFactory,需要3項內容:1.連接 2.配置 3.實體類映射關系-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!--1.數據庫連接池-->
<property name="dataSource" ref="myDataSource"></property>
<!--2.相關hibernate的配置信息-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!--3.實體類映射關系-->
<property name="packagesToScan" value="com.nf"></property>
</bean>

<!--事務管理器配置,Hibernate單數據源事務-->
<bean id="defaultTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--使用注解annotation定義事務-->
<tx:annotation-driven transaction-manager="defaultTransactionManager" ></tx:annotation-driven>


</beans>

具體內容如下:(這是與MySQL數據庫連接的配置)

#database information
driverClass=com.mysql.cj.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/lib?serverTimezone=UTC
user=root
password=

 

struts.xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
<constant name="struts.objectFactory" value="spring"></constant>
<package name="myPackage" extends="struts-default,json-default">
<action name="bookAction_*" class="bookAction" method="{1}">
<result type="json" name="jsonOK">
<param name="root">jsonMap</param>
</result>
<allowed-methods>getAllBook,getLikeBook</allowed-methods>
</action>

</package>
</struts>

 配置web.xml過濾文件

web.xml具體內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!--2個struts的過濾器-->
<filter>
<filter-name>struts-prepare</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareFilter</filter-class>
</filter>
<filter>
<filter-name>struts-execute</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-prepare</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts-execute</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--1個spring的監聽器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>

4.在web目錄下創建個js文件夾來存放這倆個js文件(注:這倆個文件是第三方的js文件):

在webContext目錄下建個jsp文件,如:test.jsp

(具體內容如下:)

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1px" id="myView">

<tr>
<td colspan="3">
<span>請輸入書名:</span>
<input name="bookName" id="bookName"/>
<img src="img/se.png" v-on:click="queryBook">
</td>
</tr>


<tr>
<th>ID</th>
<th>書名</th>
<th>價格</th>
</tr>
<tr v-for="book in bookList">
<td>{{book.id}}</td>
<td>{{book.name}}</td>
<td>{{book.price}}</td>
</tr>
</table>
</body>
<script src="${pageContext.request.contextPath}/js/vue.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">

//bookList不能為空,否則會跟view綁定失敗
var clientInput = {bookName:''};//此JSON目的用於提交給服務器查詢用的
var myModel = {bookList:[]};


var myViewModel = new Vue({
el:"#myView" ,
data:myModel,

methods{

  queryBook : function(){

  clientInput.bookName = $("#bookName").val() ;

  $.ajax({

    url:bookAction_getListBook,//url路徑

    type:"GET",//傳送方式

    data:clientInput,//傳送給后台的數據

    dataType:json,

    timeout:2000,//響應時間,這里是2秒

    success:funtion(result){//成功會執行,並把結果響應給后台

    myModel.bookList = result.bookList ;

  },

    error: funtion(){

      alert("服務器忙,請稍后再試") ;

    }

  });

}

}

}) ;
/*
var myViewModel = new Vue({
el:'#myView',
data:myModel
});
*/
//寫成函數的目的,為了【復用】
function getData(){
$.ajax({
url:"bookAction_getAllBook", //后端的API地址
type:'GET', //http:POST/GET
//data:postData, //指客戶端提交給后台的參數
dataType:'json', //服務端返回類型text,json
timeout:3000,
success:function(result){
//alert(result);
//$.extend(true, result, myModel);
//失敗
//myViewModel.data = result;
//失敗
//myModel = result;
myModel.bookList = result.bookList ;

},
error:function(){
alert('服務器忙,請不要說臟話,理論上大家都是文明人');
}
});
}
getData();


</script>
</html>

6.開始在src目錄下寫后台代碼了

先從開始:

創建Book.java文件

具體內容如下:

package com.nf.entity;

import javax.persistence.*;

@Entity
@Table(name = "book")
public class Book {
private Integer id;
private String name;
private Integer price;

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name="id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}

@Column(name = "name",length = 50,nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Column(name = "price",nullable = false)
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}

}

 

然后在創建dao模層,

先創建個BookDao接口,具體內容如下:

package com.nf.dao;

import com.nf.entity.Book;

import java.util.List;

public interface BookDao {

public List<Book> getAllBook();//查詢全部數據

pulblic List<Book> getLikeBook(String bookName) ;

}

在創建個BookDaoImpl類並實現BookDao接口,內容如下:

package com.nf.dao;

import com.nf.entity.Book;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Scope("prototype")
public class BookDaoImpl implements BookDao {

@Autowired
private SessionFactory sessionFactory;

public List<Book> getAllBook() {
Session session = sessionFactory.getCurrentSession();
Query<Book> query = session.createQuery("from Book", Book.class);
List<Book> bookList = query.getResultList();


return bookList;
}

 public List<Book> getLikeBook(String bookName){

  Session session = sessionFactory.getCurrentSession() ;

   Query<Book> q =  session.createQuery("from Book where name like : name",Book.class) ;

  q.setParameter("name","%"+bookName+"%") ;

  List<Book> bookList = q.getResultList() ;

  return bookList ;

}
}

 

最后寫模塊

(具體內容如下:)

package com.nf.action;

import com.nf.entity.Book;
import com.nf.service.BookService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
public class BookAction extends ActionSupport {

private String bookName = null ;

public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}


private Map<String,Object> jsonMap = new HashMap();
public Map<String, Object> getJsonMap() {
return jsonMap;
}
public void setJsonMap(Map<String, Object> jsonMap) {
this.jsonMap = jsonMap;
}

@Autowired
private BookService bookService;

public String getAllBook(){
List<Book> bookList = bookService.getAllBook();
jsonMap.put("bookList", bookList);
return "jsonOK";
}

public String getListBook(){

  List<Book> bookList = bookService.getListBook(bookName) ;
  jsonMap.put("bookList",bookList) ;

  return "jsonOk" ;

}

 

當查詢全部是效果圖:

(當根據模糊查詢來查的)也就是輸入書名來查找效果圖:

//根據書名的來查詢(如:輸入‘’的‘’字,就會根據的字來查詢到有‘’的‘’的書名的書)

 

//堅持比努力可拍,一天一天的堅持,會迎來結果的那一天!

 //個人的理解筆記,請勿噴!

 

 

 

 

 

 

 

 

 

 

 

 

 


}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM