Springboot整合solr+thymeleaf案例

Springboot整合solr+thymeleaf案例


这里主要通过一个案例来说一哈Springboot整合solr中遇到的问题和注意点。

首先了solr配置那些弄好,如果solr配置没弄好的 点击这里 可以看哈solr配置的详细步骤。然后我们在solr中新建一个 new_core 这个名字自己随便取无所谓,新建core的目的就是分类管理的意思,个人习惯。

这里如果你访问:http://localhost:8080/solr/ ,后新建core 新建不了,你就点击访问这里,有介绍解决详细办法。

准备工作弄完了,那我们直接来看案例。


首先配置pom.xml
	
	<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	  <modelVersion>4.0.0</modelVersion>
	  <groupId>z_springboot_solr</groupId>
	  <artifactId>z_springboot_solr</artifactId>
	  <version>0.0.1-SNAPSHOT</version>
	  <packaging>war</packaging>
	  <name>z_springboot_solr</name>
	  <description/>
	  
	  <!-- Spring Boot 启动父依赖 -->
	   <parent>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-parent</artifactId>
	        <version>1.5.3.RELEASE</version>
	        <relativePath/> 
	    </parent>
	
	  <properties>
	    	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	        <java.version>1.8</java.version>
	  </properties>

	  <dependencies>
	 
	    		<!-- solr依赖-->
	    		<dependency>
				    <groupId>org.springframework.boot</groupId>
				    <artifactId>spring-boot-starter-data-solr</artifactId>
				</dependency>
				
			    <dependency>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-aop</artifactId>
		        </dependency>
		        <dependency>
		            <groupId>org.mybatis.spring.boot</groupId>
		            <artifactId>mybatis-spring-boot-starter</artifactId>
		            <version>1.3.0</version>
		        </dependency>
		        <dependency>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-thymeleaf</artifactId>
		        </dependency>
		        <dependency>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-web</artifactId>
		        </dependency>
		        <dependency>
		            <groupId>mysql</groupId>
		            <artifactId>mysql-connector-java</artifactId>
		            <scope>runtime</scope>
		        </dependency>
		        <dependency>
		            <groupId>org.springframework.boot</groupId>
		            <artifactId>spring-boot-starter-test</artifactId>
		            <scope>test</scope>
		        </dependency>
		        <dependency>
		            <groupId>net.sourceforge.nekohtml</groupId>
		            <artifactId>nekohtml</artifactId>
		            <version>1.9.15</version>
		        </dependency>
		        <dependency>
		            <groupId>com.xiaoleilu</groupId>
		            <artifactId>hutool-all</artifactId>
		            <version>3.0.6</version>
		        </dependency>		        
			    <dependency>
					<groupId>com.fasterxml.jackson.core</groupId>
					<artifactId>jackson-core</artifactId>
					<version>2.9.6</version>
				</dependency>
				<dependency>
					<groupId>com.fasterxml.jackson.core</groupId>
					<artifactId>jackson-annotations</artifactId>
					<version>2.9.6</version>
				</dependency>
				<dependency>
					<groupId>com.fasterxml.jackson.core</groupId>
					<artifactId>jackson-databind</artifactId>
					<version>2.9.6</version>
				</dependency>
	  </dependencies>
	 
	  <build>
	    <plugins>
	     <plugin>
	            <groupId>org.springframework.boot</groupId>
	            <artifactId>spring-boot-maven-plugin</artifactId>
	       </plugin>
	    </plugins>
	  </build>
	</project>
application.yml 配置
	# 配置数据源
	spring:
	  datasource:
	    driver-class-name: com.mysql.jdbc.Driver
	    url: jdbc:mysql://localhost:3306/sbt?useUnicode=true&characterEncoding=utf8
	    username: root
	    password: 154355
	    
	# 配置solr
	  data:
	    solr:
	      host: http://localhost:8080/solr/new_core
	      #提醒哈,这里new_core,是你在开始新建core的名字
	
	# thymeleaf 相关设置
	  thymeleaf:
	    
	    prefix: classpath:/templates/
	    cache: false
	    suffix: .html
	    encoding: UTF-8
	    content-type: text/html
	    mode: LEGACYHTML5
	        
	# 设置端口号    
	server:
	   port: 8081
	
	#开MYBATIS日志打印 修改level及包名级别为debug 设置日志保存目录
	logging:
	  level:
	    net.vv2.baby.mapper: DEBUG
	  file: var/log/myapp.log

application.properties
	web.upload-path=/Users/jack/Desktop
	spring.resources.static-locations=classpath\:/META-INF/resources/,classpath\:/resources/,
									  classpath\:/static/,classpath\:/config/,classpath\:/templates/,
									  file\:${web.upload-path} 
实体类
	import org.apache.solr.client.solrj.beans.Field;
	import org.springframework.data.annotation.Id;
	public class Address {
		@Id
	    @Field("id")
		private int id;
	    @Field("userName")
		private String userName;
	    @Field("userTel")
		private String userTel;
	    @Field("province")
		private String province;
	    @Field("city")
		private String city;
	    @Field("dist")
		private String dist;	
	    @Field("street")
		private String street;
		
		get、set方法...
mapper
	@Mapper
	public interface AddressMapper {
		
		@Select("select id,userName,userTel,province,city,dist,street from tbl_address")
		public List<Address> getItemList();
		
		@Update("update tbl_address set userName=#{userName},userTel=#{userTel},province=#{province},"
				+ "city=#{city},dist=#{dist},street=#{street} where id=#{id}")
		int  updateAddress(Address address);
		
		@Delete("delete from tbl_address where id=#{id}")
		int deleteAddress(Integer id);
		
		@Insert("insert into tbl_address(userName,userTel,province,city,dist,street)"
				+ "values(#{userName},#{userTel},#{province},#{city},#{dist},#{street})")
		int addAddress(Address address);
	}
service层接口实现类

	import java.util.List;
	import org.apache.solr.client.solrj.SolrClient;
	import org.apache.solr.common.SolrInputDocument;
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.stereotype.Service;
	import com.java.solr.mapper.AddressMapper;
	import com.java.solr.model.Address;
	import com.java.solr.service.AddressService;
	@Service
	public class AddressServiceImpl implements AddressService {
		@Autowired
		private AddressMapper addressMapper;
		@Autowired
		private SolrClient solrClient;
		
		/*
		 *方法主要目的是将数据中的数据导入到solr中
		 */
		@Override
		public void importItemToIndex() throws Exception {
			
		 List<Address> itemList = addressMapper.getItemList();
	
			for (Address address : itemList) {
				SolrInputDocument document = new SolrInputDocument();
				document.setField("id", address.getId());
				document.setField("userName", address.getUserName());
				document.setField("userTel", address.getUserTel());
				document.setField("province", address.getProvince());
				document.setField("city", address.getCity());
				document.setField("dist", address.getDist());
				document.setField("street", address.getStreet());
				//添加数据对象
				solrClient.add(document);
			}
				//提交事务
			   solrClient.commit();
		}
	}
	

控制层


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.java.solr.mapper.AddressMapper;
import com.java.solr.model.Address;
import com.java.solr.service.AddressService;

@Controller
public class SolrHandler {	
	@Autowired
	private AddressMapper addressMapper;
	@Autowired
	private AddressService addressService;
	@Autowired
	private SolrClient solrClient;
	
	//这里是为了测试的时候方便请求
	@RequestMapping("/")
	 String index() {
		return "redirect:importall";
	}
	
	//导入数据
	@RequestMapping(value="/importall",method = RequestMethod.GET)
	
	public String importAll(Map<String,Object> map) {
		try {
			addressService.importItemToIndex();
			System.out.println("*****导出数据成功******");
			return "redirect:showAll";
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("!!!!导出数据失败!!!!");
		}
		return "导入数据失败!!!";
	}

	//这里是从solr中导出数据到界面显示,,模拟分页
	@RequestMapping(value = "/showAll")
	public String showAll(Model model,String keywords) throws Exception {

		int pageNo = 1;			//开始页数
		int pageSize = 10;		//每页大小

		SolrQuery solrQuery = new SolrQuery();
			
		if(StringUtils.isBlank(keywords)){
			//搜索
			solrQuery.setQuery("*:*");
		}else{
			//关键字搜索
			solrQuery.setQuery(keywords);
			
			solrQuery.set("df", "address_keywords");
		}
		
		//分页参数赋值
		solrQuery.setStart((pageNo - 1) * pageSize);
		solrQuery.setRows(pageSize);
		
		QueryResponse response = null;

		try {
			response = solrClient.query(solrQuery);
		} catch (SolrServerException e) {
			e.printStackTrace();
			return null;
		}
		
		//获得数据集合
		SolrDocumentList lists = response.getResults();
		//这里是返回界面的数据集合
		List<Address> items = new ArrayList<Address>();
		//数据总条数
		long totalRow = Long.valueOf(response.getResults().getNumFound()).intValue();
		
		System.out.println("总条数为:" + totalRow);

		
		for (SolrDocument solrDocument : lists) {
			Address address = new Address();
			address.setId(Integer.parseInt(solrDocument.get("id").toString()));
			address.setUserName(solrDocument.get("userName").toString());
			address.setUserTel(solrDocument.get("userTel").toString());
			address.setProvince(solrDocument.get("province").toString());
			address.setCity(solrDocument.get("city").toString());
			address.setDist(solrDocument.get("dist").toString());
			address.setStreet(solrDocument.get("street").toString());
			items.add(address);
		}
		//添加数据集合到request作用域中
		model.addAttribute("lists", items);

		return "pages/showAll";
	}
	
	/*
	 * 通过id查询详情
	 */
	@RequestMapping("queryById")
	public String queryById(String id,Model model) throws Exception{
		
			SolrDocument solrDocument = solrClient.getById(id);
	       
			Address address = new Address();
			address.setId(Integer.parseInt(solrDocument.get("id").toString()));
			address.setUserName(solrDocument.get("userName").toString());
			address.setUserTel(solrDocument.get("userTel").toString());
			address.setProvince(solrDocument.get("province").toString());
			address.setCity(solrDocument.get("city").toString());
			address.setDist(solrDocument.get("dist").toString());
			address.setStreet(solrDocument.get("street").toString());

			model.addAttribute("Address", address);
		
		return "pages/details";
	}
	
	/*
	 * 修改
	 */
	@RequestMapping("updateAddress")
	public String updateAddress(Address address) throws Exception{
		/*
		 * 这里说一哈 如果 solr中有 “address.getId()  这个 “id” 
		 * 那么 solr是进行的修改功能,如果没有,则是进行的增加功能。
		 */
		SolrInputDocument document = new SolrInputDocument();	
		document.setField("id", address.getId());
		document.setField("userName", address.getUserName());
		document.setField("userTel", address.getUserTel());
		document.setField("province", address.getProvince());
		document.setField("city", address.getCity());
		document.setField("dist", address.getDist());
		document.setField("street", address.getStreet());
		//添加数据对象
		solrClient.add(document);
		//提交事务
	     solrClient.commit();
	     
	     int num=addressMapper.updateAddress(address);
	     if(num>0){
				System.out.println("数据中数据同步修改成功.....");
			}else{
				System.out.println("数据中数据同步修改失败.....");
			}
	     
	     return "redirect:showAll";
	}	
		
	//删除slor中全部的数据,没有删除数据库中的数据。
	@RequestMapping(value="deleteAll",method=RequestMethod.GET)
	public String deleteAll(){
		try {
			solrClient.deleteByQuery("*:*");
			solrClient.commit();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "redirect:showAll";
	}
	//删除slor中单个数据,没有删除数据库中的数据。
	@RequestMapping(value="deleteById",method=RequestMethod.GET)
	public String deleteById(String id) throws Exception{
				//删除slor中的数据,没有删除数据库中的数据。
				solrClient.deleteByQuery("id:"+id);
				solrClient.commit();
				//删除删除数据库中的数据。	
				int num=addressMapper.deleteAddress(Integer.parseInt(id));
				if(num>0){
					System.out.println("数据中数据删除成功.....");
				}else{
					System.out.println("数据中数据删除失败.....");
				}
			return "redirect:showAll";
		}

}

showAll.html
<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org" lang="en">
  <head>
    <title>showAll.html</title>
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
  </head>
   <body>
	 <form th:action="@{/showAll}" method="post">
		请输入:<input type="text" name="keywords">
		<input type="submit" value="搜索">
	</form>
	<hr/>
	<table border="1" cellpadding="10" cellspacing="0">
		<tr>
			<th>编号</th>
			<th>姓名</th>
			<th>电话</th>
			<th></th>
			<th></th>
			<th></th>
			<th></th>
			<th>操作</th>
		</tr>
			<tr th:each="addr:${lists}">
				<td th:text="${addr.id}"></td>
				<td th:text="${addr.userName}"></td>
				<td th:text="${addr.userTel}"></td>
				<td th:text="${addr.province}"></td>
				<td th:text="${addr.city}"></td>
				<td th:text="${addr.dist}"></td>
				<td th:text="${addr.street}"></td>
				<td>
				<a th:href="@{/deleteById(id=${addr.id})}">删除</a>
				&nbsp;
				<a th:href="@{/queryById(id=${addr.id})}">详情</a>
				</td>
			</tr>
	</table>
		<a th:href="@{/deleteAll}">删除Solr中所有的数据</a>
  </body>
</html>
details.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
  <head>
    <title>详情</title>
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
  </head>
  <body>		
  	<form th:action="@{/updateAddress}" method="post"  th:object="${Address}" >
  		<table border="0.5" cellpadding="0px" cellspacing="5px">
  		<tr><td>
  		 id<br>	
  			<input type="text" name="id" th:field="*{id}" >
  		</td></tr><tr><td>	
  		userName<br>
  				 <input type="text" name="userName" th:field="*{userName}" >
  		</td></tr><tr><td>
  		userTel<br>
  				<input type="text" name="userTel" th:field="*{userTel}" >
  		</td></tr><tr><td>
  		city<br>
  			 <input type="text" name="city" th:field="*{city}" >
  		</td></tr><tr><td>
  		dist<br>
  			 <input type="text" name="dist" th:field="*{dist}" >
  		</td></tr><tr><td>					
  		street<br>
  			<input type="text" name="street" th:field="*{street}">
		</td></tr><tr><td>					
  		province<br>
  				 <input type="text" name="province" th:field="*{province}">
		</td></tr>
		</table><br><br>
			<input type="submit" value="save">
  		</form>		
  </body>
</html>

没了,写的有点挫,适合小白看哈。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值