流程
- tomcat+solr
- SSM
- SSM+(tomcat+solr)
工具版本
- tomcat:7.0.56
- solr:4.10.3
1.SSM+tomcat
解压一个干净的tomcat
-
修改tomcat中conf包下的tomcat-users.xml文件(tomcat有关用户的配置)
- 在文件的中添加一下代码(文件尾部有类型内容,被注释掉了)
<role rolename="manager-gui"/> <role rolename="manager-script"/> <role rolename="manager-jmx"/> <role rolename="manager-status"/> <user username="yanm" password="yanm" roles="manager-gui, manager-script, manager-jmx, manager-status"/>
启动tomcat,输入用户名和密码进入管理界面,tomcat就完成了有关用户的配置
- 进入一下界面,就说明用户配置完成
将solr-dist-solr.war复制到tomcat-webapps下
重新启动tomcat
将solr-example-lib-ext下的所有包拷贝到tomcat-webapps-solr-WEB-INF-lib中
将solr-example-resource-log4j.properties复制到tomcat-webapps-solr-WEB-INF-classes下(classes是新建的,名字必须是这个名字)
新建solr_home文件夹,并将solr-example-solr-collection1(是整个文件下,不是文件夹下的内容)复制到solr_home下
-
修改tomcat-webapps-solr-WEB-INF-web.xml文件(配置solr_home的位置)
- 解注其中的< env-entry>文件,并将solr_home的路径修改
<env-entry> <env-entry-name>solr/home</env-entry-name> <env-entry-value>D:/Java/solr/solr2/solr_home</env-entry-value> <env-entry-type>java.lang.String</env-entry-type> </env-entry>
启动tomcat,访问
- 出现以下界面说明,solr+tomcat已经配置完成
-
安装中文分词器
-
配置 IKAnalyzer 的 jar 包
- 将solr安装包下的IK Analyzer 2012FF_hf1包下 IKAnalyzer2012FF_u1.jar 拷⻉到 Tomcat 的webapps/solr/WEB-INF/lib 下。
-
IKAnalyzer 的配置⽂件
- 在 Tomcat的webapps/solr/WEB-INF/ 下创建 classes ⽬录。(tomcat+solr时 已经新建过了)
- 将 IKAnalyzer.cfg.xml、ext_stopword.dic 、mydict.dic copy 到 Tomcat的
webapps/solr/WEB-INF/classes
-
修改schema.xml文件(solr_home-collection1-conf下)
<fieldType name="text_ik" class="solr.TextField"> <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/> </fieldType>
验证是否完成
-
2.搭建SSM项目
-
pom文件中添加依赖
<packaging>war</packaging> <properties> <!--统一管理spring所有的版本--> <spring-version>4.3.6.RELEASE</spring-version> </properties> <dependencies> <!--jsp--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> <!--避免冲突--> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> <!--避免冲突--> </dependency> <!--jstl--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--springmvc的依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <!--rest风格使用--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.10</version> </dependency> <!--mysql--> <!--<dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>2.5.0</version> </dependency>--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <!--mybatis spring的插件,将mybatis交给spring来管理--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!--spring的单元测试--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> <!--spring jdbc,包含事务--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-version}</version> </dependency> <!-- spring aop的面向切面的配置--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.0</version> </dependency> <!--druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.15</version> </dependency> <!--日志信息--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> <scope>provided</scope> </dependency> <!--为了使用@Resource注解--> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <!--solr依赖--> <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>4.10.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> </dependencies> <build> <!--不过滤java下的xml文件--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <!-- define the project compile level --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- 添加tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>80</port> </configuration> </plugin> </plugins> </build>
新建webapp包,并在包下新建WEB-INF包和index.html页面
-
在WEB-INF包下新建web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置springmvc--> <servlet> <servlet-name>springDispatcherServlet</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> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 使用springk框架写好的中文乱码过滤器来实现乱码的处理 --> <filter> <filter-name>encode</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
-
resource包下的db.properties文件
url=jdbc:mysql://localhost:3307/solr?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 driver=com.mysql.cj.jdbc.Driver uname=root upass=root solr_server_url=http://localhost:8080/solr
-
resource包下的log4j.properties文件(使用log4j第三方日志包)
# 全局日志配置 # 共有四个级别 ERROE,DEBUG,WARN,INFO log4j.rootLogger=ERROR, stdout, F # MyBatis 日志配置,可以指定到包下,也可以指定到类上,也可以指定到类中的某一个方法 log4j.logger.com.yanm.dao.IUserDao=TRACE # 控制台输出 log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%6p [%t] - %m%n #打印到文件myproj.log中 log4j.appender.F = org.apache.log4j.DailyRollingFileAppender log4j.appender.F.File =myproj.log log4j.appender.F.Append = true log4j.appender.F.Threshold = ERROE log4j.appender.F.layout=org.apache.log4j.PatternLayout log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
-
resource包下的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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--设置ssm项目的注解配置--> <!--<context:annotation-config />--> <!--与下面的包扫描重复了--> <!--设置包扫描,分别扫描controller和service包--> <context:component-scan base-package="com.ym.controller"/> <context:component-scan base-package="com.ym.service" /> <!--注解驱动--> <mvc:annotation-driven /> <!--配置默认资源可以被访问--> <mvc:default-servlet-handler /> <!--引入spring和mybatis的整合文件--> <import resource="classpath:spring-mybatis.xml" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
-
resource包下的spring-mybatis.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" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--引入数据库的配置文件信息--> <context:property-placeholder location="classpath:db.properties" /> <!--druid数据源--> <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="${url}" /> <property name="driverClassName" value="${driver}" /> <property name="username" value="${uname}" /> <property name="password" value="${upass}" /> </bean> <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="typeAliasesPackage" value="com.ym.entity" /> <property name="mapperLocations" value="classpath*:dao/*Dao.xml" /> <property name="dataSource" ref="ds" /> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ym.dao" /> <property name="sqlSessionFactoryBeanName" value="ssfb"/> </bean> <!--配置事务管理器--> <bean id="dstm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="ds"/> </bean> <!--声明事务的实现方式 以这些关键字开头的方法分别设置事务的隔离级别以及出错后的操作--> <tx:advice id="tx" transaction-manager="dstm"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="mpt" expression="execution(* com.ym.service.*.*(..))"/> <aop:advisor advice-ref="tx" pointcut-ref="mpt"/> </aop:config> <!--添加扫描,对service层进行单元测试的时候,一定要定位到service包下--> <context:component-scan base-package="com.ym.service" /> </beans>
-
resource包下的mybatis-config.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--给当前mybatis项目添加日志功能,采用第三方日志jar包--> <settings> <setting name="logImpl" value="LOG4J"/> </settings> </configuration>
SSM项目搭建,可以写逻辑代码了
-
entity层
- SolrData.java : 这是根据联合查询做的一个dto,应该放到dto下,现先放在entity下
package com.ym.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //写的是一个Dto,应该放在dto包下,现在临时放在entity下, @Data @AllArgsConstructor @NoArgsConstructor public class SolrData { private long id; private String title; private String sellPoint; private long price; private String image; private String catName; private String itemDesc; }
-
dao层接口
- SolrDataDao.java : 接口
package com.ym.dao; import com.ym.entity.SolrData; import java.util.List; public interface SolrDataDao { List<SolrData> getAllData(); }
-
与接口对应的mapper文件
- SolrDataDao.xml : 使用联合查询,返回结果映射成SolrData的类型
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ym.dao.SolrDataDao"> <select id="getAllData" resultType="SolrData"> SELECT i.id,i.title,i.sell_point sellPoint ,i.price,i.image,c.name catName,d.item_desc itemDesc FROM tb_item i, tb_item_cat c, tb_item_desc d WHERE i.cid=c.id AND i.id =d.item_id </select> </mapper>
-
service层接口及实现类
- ISolrDataService : 接口
- SolrDataServiceImpl.java : 接口的实现类
package com.ym.service; import com.ym.entity.SolrData; import java.util.List; public interface ISolrDataService { //查询所有信息 List<SolrData> getAllData(); //判断是否已经写到solr中去了 boolean dataFromDB2Solr(); }
- 实现类
package com.ym.service.impl; import com.ym.dao.SolrDataDao; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.util.List; @Service public class SolrDataServiceImpl implements ISolrDataService { @Resource private SolrDataDao solrDataDao; @Value("${solr_server_url}") //@Value注解,就可以拿到db中的solr_server_url的值 private String baseURL; @Override public List<SolrData> getAllData() { List<SolrData> solrDatas = solrDataDao.getAllData(); return solrDatas; } @Override public boolean dataFromDB2Solr() { List<SolrData>list=getAllData(); //连接solr服务器 HttpSolrServer server=new HttpSolrServer(baseURL); //创建文档对象 SolrInputDocument document=null; try { for (SolrData sd : list) { document=new SolrInputDocument(); //setField的name值一定要和schema.xml中的field中的值一定要相同,并且schema.xml中的field值不能重复, // schema.xml中的field的值一定要和查询的字段相对应,可以不一样,但是一定要对应 document.setField("id",sd.getId()); document.setField("item_title",sd.getTitle()); document.setField("item_sell_point",sd.getSellPoint()); document.setField("item_price",sd.getPrice()); document.setField("item_image",sd.getImage()); document.setField("item_category_name",sd.getCatName()); document.setField("item_desc",sd.getItemDesc()); //向服务器中写入文档 server.add(document); } //向服务器中提交 server.commit(); return true; } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } }
-
controller层
- SolrDataController.java
package com.ym.controller; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; @RestController public class SolrDataController { @Resource private ISolrDataService solrDataService; //测试能否获取到内容 @GetMapping("/solrData") public List<SolrData> getAllData(){ List<SolrData> datas = solrDataService.getAllData(); return datas; } @GetMapping("/dataFromDB2Solr") public boolean dataFromDB2Solr(){ return solrDataService.dataFromDB2Solr(); } }
3.SSM+(tomcat+solr)
-
修改scheme.xml文件(solr_home-collection1-conf下)
- 根据数据库中查询的字段添加field内容,其中添加的field必须要和数据库中的所要查询的内容对应,名字可以不一样,但是一定要对应,service层用的document对象,向solr中添加查询的内容时,也需要field中的这个name值
- service层实现类setField的name值一定要和schema.xml中的field中的值一定要相同,并且schema.xml中的field值不能重复,
<field name="item_title" type="text_ik" indexed="true" stored="true"/> <field name="item_sell_point" type="text_ik" indexed="true" stored="true"/> <field name="item_price" type="long" indexed="true" stored="true"/> <field name="item_image" type="string" indexed="false" stored="true" /> <field name="item_category_name" type="string" indexed="true" stored="true" /> <field name="item_desc" type="text_ik" indexed="true" stored="false" /> <field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/> <copyField source="item_title" dest="item_keywords"/> <copyField source="item_sell_point" dest="item_keywords"/> <copyField source="item_category_name" dest="item_keywords"/> <copyField source="item_desc" dest="item_keywords"/>
solr下的tomcat
启动SSM项目
请求SSM项目中的
/dataFromDB2Solr
请求访问solr下的tomcat验证是否配置完成
4.关键字查询,并使用分词器,设置关键字高亮
- 此时是从solr服务器中取数据,而不是从数据库中查询
- 修改SSM项目的代码
-
service层接口及实现类
- ISolrDataService : 接口
- SolrDataServiceImpl.java : 接口的实现类
package com.ym.service; import com.ym.entity.SolrData; import java.util.List; public interface ISolrDataService { //从数据库中找 List<SolrData> getAllData(); //将从从数据库中查询的内容,保存到solr中 boolean dataFromDB2Solr(); //从solr中查找 List<SolrData> getAllDataFromSolr(String keyword); }
- 实现类
package com.ym.service.impl; import com.ym.dao.SolrDataDao; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class SolrDataServiceImpl implements ISolrDataService { @Resource private SolrDataDao solrDataDao; /** * 通过value注解将db.properties文件中的solr_server_url注入给baseUrl */ @Value("${solr_server_url}") private String baseURL; //从数据库中获取查询的内容 @Override public List<SolrData> getAllData() { List<SolrData> solrDatas = solrDataDao.getAllData(); return solrDatas; } //将从数据库中的内容,保存到solr中 @Override public boolean dataFromDB2Solr() { List<SolrData>list=getAllData(); //连接solr服务器 HttpSolrServer server=new HttpSolrServer(baseURL); //创建文档对象 SolrInputDocument document=null; try { for (SolrData sd : list) { document=new SolrInputDocument(); //setField的name值一定要和schema.xml中的field中的值一定要相同,并且schema.xml中的field值不能重复, // schema.xml中的field的值一定要和查询的字段相对应,可以不一样,但是一定要对应 document.setField("id",sd.getId()); document.setField("item_title",sd.getTitle()); document.setField("item_sell_point",sd.getSellPoint()); document.setField("item_price",sd.getPrice()); document.setField("item_image",sd.getImage()); document.setField("item_category_name",sd.getCatName()); document.setField("item_desc",sd.getItemDesc()); //向服务器中写入文档 server.add(document); } //向服务器中提交 server.commit(); return true; } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } /** * Description: 在solr中查询获取内容:根据关键字,包含分词,高亮 * @author: YanM * @param: * @return: */ @Override public List<SolrData> getAllDataFromSolr(String keyword) { List<SolrData> solrDatas=null; //借助baseURL来创建一个httpSolrService对象 HttpSolrServer server=new HttpSolrServer(baseURL); //创建一个solrQuery对象 SolrQuery query=new SolrQuery(); try { //如果要检索的关键字为空,则全查 if (StringUtils.isEmpty(keyword)){ query.setQuery("*:*"); }else { query.setQuery(keyword); } //设置df,默认的查询字段,在item_title上实现检索 query.set("df","item_title"); //设置start的值,返回的结果的第几条记录开始,一般分页的时候使用,默认从0开始 query.set("start",0); //设置rows的值,值定返回结果最多多少条记录,默认是10,配合start实现分页 query.set("rows",30); //通过query对象的setHight(boolean)来设置查询可高亮显示 query.setHighlight(true); //开启高亮组件,或用query.setParam("hl","true") //设置高亮的域 query.addHighlightField("item_title"); //高亮字段 //设置高亮的前缀 query.setHighlightSimplePre("<font color='red'>");//标记,高亮关键字前缀 //设置高亮的后缀 query.setHighlightSimplePost("</font>"); //标记,高亮关键字后缀 //System.out.println(query); //使用之前创建的httpSolrService对象调用query(query)方法将query对象所设置的查询条件加入进来得到一个查询响应对象 QueryResponse response=server.query(query); //通过查询响应对象的getResult()方法的到SolrDocumentList对象 Map<String,Map<String,List<String>>> map=response.getHighlighting(); SolrDocumentList list = response.getResults(); if (list!=null&&list.size()!=0){ solrDatas=new ArrayList<>(); SolrData s=null; //遍历得到的SolrDocumentList对象 for (SolrDocument sd : list) { s=new SolrData(); //SolrDocument对象的get(name)默认返回值为object Object oid = sd.getFieldValue("id"); //将oid转换为long类型 long id=oid==null ?0:Long.parseLong((String)oid); s.setId(id); //通过高亮map对象设置solrData的title属性 s.setTitle(map.get(sd.getFieldValue("id")).get("item_title").get(0)); Object oprice = sd.getFieldValue("item_price"); long price =oprice==null?0:((long) oprice); //设置价格 s.setPrice(price); //设置卖点 s.setSellPoint((String)sd.getFieldValue("item_sell_point")); //设置图片 s.setImage((String)sd.getFieldValue("item_image")); //设置商品种类名称 s.setCatName((String)sd.getFieldValue("item_category_name")); //设置条目描述 s.setItemDesc((String)sd.getFieldValue("item_desc")); //将solrData对象加入到列表中 solrDatas.add(s); } return solrDatas; } } catch (SolrServerException e) { e.printStackTrace(); } return null; } }
-
controller层
- SolrDataController.java
package com.ym.controller; import com.ym.entity.SolrData; import com.ym.service.ISolrDataService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; @Controller public class SolrDataController { @Resource private ISolrDataService solrDataService; //测试能否获取到内容 @GetMapping("/solrData") @ResponseBody public List<SolrData> getAllData(){ List<SolrData> datas = solrDataService.getAllData(); return datas; } //将从数据库中的内容,保存到solr服务器中 @GetMapping("/dataFromDB2Solr") @ResponseBody public boolean dataFromDB2Solr(){ return solrDataService.dataFromDB2Solr(); } //从solr中查找数据(rest风格) @GetMapping("/getDataFromSolr") @ResponseBody public List<SolrData> getDataFromSolrByKeyWord(@RequestParam(value = "kw",defaultValue = "")String kw){ return solrDataService.getAllDataFromSolr(kw); } //从solr中查找数据,并且返回到页面 @PostMapping("/getDataFromSolrByKeyWord") public String searchPage(@RequestParam(value = "kw",defaultValue = "")String kw, Model model){ model.addAttribute("datas",solrDataService.getAllDataFromSolr(kw)); return "search"; } }
-
前端查询页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>this is search page</h1> <form action="/getDataFromSolrByKeyWord" method="post"> KeyWard : <input type="text" name="kw"> <input type="submit" value="search"> </form> </body> </html>
-
前端查询结果显示
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>search</title> </head> <body> <h1>this is search detail</h1> <table border="1"> <tr> <th>id</th> <th>title</th> <th>sellPoint</th> <th>price</th> <th>image</th> <th>catName</th> <th>itemDesc</th> </tr> <c:forEach items="${datas}" var="s"> <tr> <td>${s.id}</td> <td>${s.title}</td> <td>${s.sellPoint}</td> <td>${s.price}</td> <td>${s.image}</td> <td>${s.catName}</td> <td>${s.itemDesc}</td> </tr> </c:forEach> </table> </body> </html>
-
过程演示
-
输入"老人机",看查看结果
-
页面显示查询结果
-