<!--1.添加spring框架需要的jarbao-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.15.RELEASE</version>
</dependency>
<!--2.mybatis-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--配置日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--导入spring整合mybatis的包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<!--springm-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<!--jstl-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>jstl</artifactId>-->
<!--<version>1.2</version>-->
<!--</dependency>-->
<!--加入分页需要的jar包-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!--jsp和servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--8.thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)web.xml
<!-- 配置监听器 读spring的配置文件的 -->
<!-- 配置spring...xml文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- 配置context 加载的监听器 -->
<!-- 加载spring 的容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置thymeleaf 让前端控制器放行.html页面 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
3)资源文件
db.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sc?characterEncoding=utf-8
uname=root
pwd=
spring.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"
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">
<!-- 1.配置需要扫描的包 -->
<context:component-scan base-package="com.test" />
<!-- 2.导入db.properties文件-->
<context:property-placeholder location="classpath:db.properties" />
<!-- 3.创建数据源对象 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${url}" />
<property name="user" value="${uname}" />
<property name="password" value="${pwd}" />
</bean>
<!-- 4.创建sqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
</bean>
<!-- 5. 创建ItemsMapper的代理 替代dao层的操作 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.test.mapper" />
</bean>
</beans>
springmvc.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:p="http://www.springframework.org/schema/p"
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">
<!-- 1. 配置 需要扫描的控制层在哪个包 -->
<context:component-scan base-package="com.test.controller"></context:component-scan>
<!-- 2 配置 视图解析器 中的 前缀和后缀 -->
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--<!– 设置前缀 –>-->
<!--<property name="prefix" value="/WEB-INF/"/>-->
<!--<!– 设置后缀 –>-->
<!--<property name="suffix" value=".jsp"/>-->
<!--</bean>-->
<!-- 3.配置的是thymeleaf模板 -->
<!-- 使用thymeleaf解析 -->
<bean id="templateResolver"
class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/html/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
<property name="cacheable" value="false" />
<property name="characterEncoding" value="UTF-8"/><!--不加会乱码-->
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<!--解决中文乱码-->
<property name="characterEncoding" value="UTF-8"/>
</bean>
<!--放行静态资源 文件-->
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources mapping="/assets/**" location="/assets/" />
<mvc:resources mapping="/basic/**" location="/basic/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
</beans>
<!--<?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:p="http://www.springframework.org/schema/p"-->
<!-- 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">-->
<!-- <!–1.配置需要扫描的控制层在哪个包–>-->
<!-- <context:component-scan base-package="com.test.controller"></context:component-scan>-->
<!-- <!–配置视图解析器–>-->
<!--<!– <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">–>-->
<!--<!– <property name="prefix" value="/WEB-INF/"/>–>-->
<!--<!– <property name="suffix" value=".jsp"/>–>-->
<!--<!– </bean>–>-->
<!-- <!–配置thymeleaf模板–>-->
<!-- <bean id="templateResolver"-->
<!-- class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">-->
<!-- <property name="prefix" value="/WEB-INF/html"/>-->
<!-- <property name="suffix" value=".html"/>-->
<!-- <property name="templateMode" value="HTML"/>-->
<!-- <property name="cacheable" value="false"/>-->
<!-- <property name="characterEncoding" value="UTF-8"/>-->
<!-- </bean>-->
<!-- <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">-->
<!-- <property name="templateResolver" ref="templateResolver"/>-->
<!-- </bean>-->
<!-- <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">-->
<!-- <property name="templateEngine" ref="templateEngine"/>-->
<!-- <property name="characterEncoding" value="UTF-8"/>-->
<!-- </bean>-->
<!-- <!–放行静态资源文件–>-->
<!-- <mvc:resources mapping="/assets/**" location="/assets/"/>-->
<!-- <mvc:resources mapping="/basic/**" location="/basic/" />-->
<!-- <mvc:resources mapping="/css/**" location="/css/" />-->
<!-- <mvc:resources mapping="/images/**" location="/images/" />-->
<!-- <mvc:resources mapping="/js/**" location="/js/" />-->
<!--</beans>-->
SqlMapConfig.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>
<!-- 1.配置日志管理 -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 2.配置别名-->
<typeAliases>
<package name="com.test.pojo" />
</typeAliases>
<!--<!–3 注册mapper文件 –>-->
<!--<mappers>-->
<!--<package name="com.test.mapper" />-->
<!--</mappers>-->
<!-- 3.添加分页插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>
</configuration>
public class Users {
private int user_id;
private String uname;
private String upwd;
}
创建UsersMapper接口
public interface UsersMapper {
public int addUser(Users user);
}
创建UsersMapper.xml
<?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.test.mapper.UsersMapper" >
<insert id="addUser" parameterType="Users">
insert into users(uname,upwd) values (#{uname},#{upwd})
</insert>
</mapper>
创建Service接口层
public interface IUsersService {
public int reg(Users user);
}
实现Service接口层
@Service
public class UsersService implements IUsersService {
@Autowired
private UsersMapper usersMapper;
public UsersMapper getUsersMapper() {
return usersMapper;
}
public void setUsersMapper(UsersMapper usersMapper) {
this.usersMapper = usersMapper;
}
@Override
public int reg(Users user) {
//添加用户到数据库,返回一个用户id
int i= usersMapper.addUser(user);
return i;
}
}
最后写控制层
@RequestMapping("/users")
public class UserController {
public IUsersService getusersService() {
return usersService;
}
public void setusersService(IUsersService usersService) {
this.usersService = usersService;
}
@Autowired
private IUsersService usersService;
@RequestMapping("/regUi")
public String regUi()
{
return "register";
}
@RequestMapping("/reg")
public String login(Users user)
{
int i=usersService.reg(user);
if(i==1)
return "login";
else
return "error";
}
eg:控制层拿到用户会调用service层的注册方法,把用户传进来,然后service层的方法又会调用Mapper层addUser方法传进user,最后Mapper.xml会将这个传来的user通过insert加载到数据库中完成添加操作
1.mapper层
public int isExistsUname(String uname);
.xml
<select id="isExistsUname" parameterType="String" resultType="int">
select count(*) from users where uname=#{uname}
</select>
2.Service层
public int isExistsUname(String uname);
@Override
public int isExistsUname(String uname) {
return usersMapper.isExistsUname(uname);
}
3.Controller层
@RequestMapping("/isExistsUname")
@ResponseBody
public String isExistsUname(String uname)
{
int i=usersService.isExistsUname(uname);
return i+"";
}
js文件
$(function(){
//给用户名做ajax判断
$("#uname").blur(function(){
//1.获得用户名
var uname=$(this).val();
//2.通过ajax传到服务器端判断用户是否存在
$.get("http://localhost:8080/testShop/users/isExistsUname?uname="+uname,function(msg){
//3.处理结果
if(msg=="1") {
$("#msg_span").html("该用户已存在");
$("#submit").attr("disabled",true);
}
else {
$("#msg_span").html("可以注册");
$("#submit").attr("disabled",false);
}
})
})
})
1.mapper
public Users selectUserByUnameAndUpwd(Users user);
<select id="selectUserByUnameAndUpwd" parameterType="Users" resultType="Users">
select user_id,uname,upwd from users where
uname=#{uname} and upwd=#{upwd}
</select>
2.service
public Users checkLogin(Users user);
@Override
public Users checkLogin(Users user) {
return usersMapper.selectUserByUnameAndUpwd(user);
}
3.controller
@RequestMapping("/checkLogin")
public String checkLogin(Users user, HttpServletRequest request)
{
Users loginUser=usersService.checkLogin(user);
if(loginUser!=null)
{
HttpSession session=request.getSession();
session.setAttribute("loginUser",loginUser);
return "index";
}
else {
return "error";
}
}
如果登录成功,会显示用户名
<div class="menu-hd" th:if="${session.loginUser==null}">
<a href="" th:href="@{/users/loginUi}" target="_top" class="h">亲,请登录</a>
<a href="" th:href="@{/users/regUi}" target="_top">免费注册</a>
</div>
<div class="menu-hd" th:if="${session.loginUser!=null}">
<span th:text="${session.loginUser.uname}"></span>欢迎您
</div>
public class Cart {
private int cart_id;
private int user_id;
private float total_price;
private int total_num;
}
因为Cart类属于Users实体类中,在Users类中添加Cart信息
public class Users {
private int user_id;
private String uname;
private String upwd;
private Cart cart;
}
用户是注册之后就会有一个购物车(此条代码意思是在执行完用户添加后,查询最后一次插入的ID也就是用户对应的user_id同时返回user_id)
<insert id="addUser" parameterType="Users">
-- 获取刚刚添加用户的id
<selectKey keyProperty="user_id" resultType="int" order="AFTER">
select LAST_INSERT_ID();
</selectKey>
insert into users(uname,upwd) values (#{uname},#{upwd})
</insert>
同时在注册方法进行修改
@Autowired
private CartMapper cartMapper;
public int reg(Users user) {
//添加用户到数据库,返回一个用户id
usersMapper.addUser(user);
Cart cart=new Cart();
cart.setUser_id(user.getUser_id());
cart.setTotal_num(0);
cart.setTotal_price(0);
cartMapper.addCart(cart);
System.out.println(user.getUser_id());
return user.getUser_id();
}
登录时验证用户名和密码,如果验证成功,查询相应用户的购物车信息,放入到session中
<select id="selectUserByUnameAndUpwd" parameterType="Users" resultMap="userCartMap">
select users.user_id,uname,upwd,cart_id,total_price,total_num from users,cart where users.user_id=cart.user_id
and uname=#{uname} and upwd=#{upwd}
</select>
<resultMap id="userCartMap" type="Users">
<id column="user_id" property="user_id"/>
<result column="uname" property="uname"/>
<result column="upwd" property="upwd"/>
<association property="cart" javaType="Cart">
<id column="cart_id" property="cart_id"/>
<result column="user_id" property="user_id"/>
<result column="total_price" property="total_price"/>
<result column="total_num" property="total_num"/>
</association>
</resultMap>
controller
@RequestMapping("/checkLogin")
public String checkLogin(Users user, HttpServletRequest request)
{
Users loginUser=usersService.checkLogin(user);
if(loginUser!=null)
{
HttpSession session=request.getSession();
session.setAttribute("loginUser",loginUser);
return "index";
}
else {
return "error";
}
}
前端:
<span>购物车</span><strong id="J_MiniCartNum" class="h" th:if="${session.loginUser!=null}" th:text="${session.loginUser.getCart().getTotal_num()}"></strong>
引入的jar包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
sqlMapConfig.xml配置
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>
service层
public interface IGoodsService {
//分页查询 根据条件查询商品列表
public PageInfo<Goods> showGoodsByWhere(int cid,int pageIndex,int pageSize);
}
impl
@Override
public PageInfo<Goods> showGoodsByWhere(int cid,int pageIndex,int pageSize) {
//设置开始查询的位置及查询多少条记录
PageHelper.startPage(pageIndex,pageSize);
//查询当前页数据
List<Goods> goodsList=goodsMapper.selectGoodsByCid(cid);
//组装成pageInfo对象 返回
PageInfo<Goods> pageInfo=new PageInfo<>(goodsList);
return pageInfo;
}
前端:
<li th:each="goods:${session.pageInfo.getList()}">
<div class="i-pic limit">
<img height="200px" th:src="@{${goods.goodsImg}}" />
<p class="title fl" th:text="${goods.goodsName}"></p>
<p class="price fl">
<b>¥</b>
<strong th:text="${goods.salesPrice}"></strong>
</p>
<p class="number fl">
销量<span>1110</span>
</p>
</div>
</li>
<!--分页 -->
<ul class="am-pagination am-pagination-right">
<li><a href="#">»</a></li>
<th:block th:each="pageIndex:${session.pageInfo.navigatepageNums}">
<li th:if="${session.pageInfo.pageNum==pageIndex}" class="am-active"><a href="#" th:href="@{/goods/showGoodsByWhere(pageIndex=${pageIndex},cid=${session.cid})}" th:text="${pageIndex}"></a></li>
<li th:unless="${session.pageInfo.pageNum==pageIndex}"><a href="#" th:href="@{/goods/showGoodsByWhere(pageIndex=${pageIndex},cid=${session.cid})}" th:text="${pageIndex}"></a></li>
</th:block>
<li><a href="#">»</a></li>
</ul>
solr是一个独立的企业级搜索应用服务器,它是对外提供类似于web-service的aoi接口,用户可以通过http请求,发送一定格式的xml数据到solr,生成索引,也可以发送hettp get请求,请求solr服务器查询数据,将查询出的数据也是以xml格式返回。
优点:1.数据库的模糊查询没有分词的功能,solr有,可以更有效地查询到我们需要的数据。
2.从solr服务器中查询数据会比从数据库查询速度更快
工作方式
文档通过http利用xml加到一个搜索集合中,sokr查询该集合也是通过http收到一个xml/json响应来实现。它的主要特性包括:高效、灵活的缓存功能,垂直搜索功能,高亮显示搜索结果,通过索引复制来提高可用性,提供一套强大Data Schema来定义字段,类型和设置文本分析。提供基于Web管理界面等。
下载地址:http://archive.apache.org/dist/lucene/solr/
solr文件夹解析
cmd命令模式进入到bin目录下,执行solr start 默认端口8983,访问localhost:8983/solr
创建core,每一个core代表一个索引库,里面保存索引数据以及配置信息,solr中可以有多个core,也就相当于mysql服务器下可以多个数据库
1.在命令模式 bin目录下执行solr create -c core名称
2.将下列的jar包放入到lib中3.
"text_smartcn" class="solr.TextField" positionIncrementGap="100">
type="index">
class="org.apache.lucene.analysis.cn.smart.HMMChineseTokenizerFactory"/>
</analyzer>
type="query">
class="org.apache.lucene.analysis.cn.smart.HMMChineseTokenizerFactory"/>
</analyzer>
</fieldType>
ik分词器
<!-- ik分词器 -->
"text_ik" class="solr.TextField">
type="index">
class="org.wltea.analyzer.lucene.IKTokenizerFactory" useSmart="false" conf="ik.conf"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
type="query">
class="org.wltea.analyzer.lucene.IKTokenizerFactory" useSmart="true" conf="ik.conf"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
2)将数据库数据导入solr中
mysql-connector-java.jar和
放入到
创建mysql-db文件夹存放mysql数据
再在此文件夹中创建data-config.xml文件 为了避免出错,url尽量多配
"1.0" encoding="utf-8" ?>
type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/sc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false"
user="root"
password="045617"
/>
"goods" query="select goods_id,goods_name,sales_price,goods_img from goods">
"goods_id" name="id"/>
"goods_name" name="goodsName"/>
"sales_price" name="salesPrice"/>
"good_img" name="goodsImg"/>
</entity>
</document>
</dataConfig>
在C:\solr-7.6.0\server\solr\goods\conf下的managed-schema文件第113行左右添加document中的字段信息 id是系统自动配的,不能删除
"id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
<!-- docValues are enabled by default for long type so we don't need to index the version field -->
"_version_" type="plong" indexed="false" stored="false"/>
"_root_" type="string" indexed="true" stored="false" docValues="false" />
"goodsName" type="text_ik" indexed="true" stored="true" multiValued="false" />
"salesPrice" type="plong" indexed="true" stored="true" multiValued="false" />
"goodsImg" type="string" indexed="true" stored="true" multiValued="false" />
在C:\solr-7.6.0\server\solr\goods\conf的solrconfig.xml文件765行左右添加如下信息,目的是导入data-config.xml
"/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
"defaults">
"config">mysql-db/data-config.xml</str>
</lst>
</requestHandler>
重启服务器 solr restart -p 8983,进入localhost:8983/solr执行下面配置
3)java与solr进行联系
①导入jar包
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>7.6.0</version>
</dependency>
②配置spring.xml
<!-- 配置solr客户端对象-->
<bean id="httpSolrClient"
class="org.apache.solr.client.solrj.impl.HttpSolrClient">
<constructor-arg name="builder"
value="http://localhost:8983/solr/goods"/>
</bean>
③编写代码
//注入HttpSolrClient
@Autowired
private HttpSolrClient httpSolrClient;
public HttpSolrClient getHttpSolrClient() {
return httpSolrClient;
}
public void setHttpSolrClient(HttpSolrClient httpSolrClient) {
this.httpSolrClient = httpSolrClient;
}
@RequestMapping("/showGoodsByWhereBySolr")
public ModelAndView showGoodsByWhereBySolr(@RequestParam(name="pageIndex",defaultValue = "1")int pageIndex, int cid, @RequestParam(name="keyword",defaultValue = "西装")String keyword, HttpServletRequest request) throws IOException, SolrServerException {
//通过solr客户端 查询数据
//1.创建查询对象
SolrQuery solrQuery=new SolrQuery();
//2,设置默认查询字段
solrQuery.set("df","goodsName");
solrQuery.setQuery(keyword+"*");
// 3.设置过滤条件
solrQuery.setFilterQueries("cid:"+cid);
//4.设置组装的字段
solrQuery.addField("id");
solrQuery.addField("goodsName");
solrQuery.addField("salesPrice");
solrQuery.addField("goodsImg");
//将查询对象传递到服务器端
QueryResponse queryResponse=httpSolrClient.query(solrQuery);
httpSolrClient.commit();
List<Goods>goodsList=queryResponse.getBeans(Goods.class);
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("search2");
HttpSession session=request.getSession();
session.setAttribute("goodsList",goodsList);
return modelAndView;
}
④将Goods实体序列化,对应solr组装字段的名字,id的属性要和solr设置的一致,将int改为String
public class Goods implements Serializable {
@Field("id")
private String goodsId;
@Field
private String goodsName;
@Field
private String goodsImg;
@Field
private float salesPrice;
}
⑤设置solr查询分页功能
//5.设置分页
int pageSize=2;
solrQuery.setStart((pageIndex-1)*pageSize);//设置偏移量,也就是从下标几开始找
solrQuery.setRows(pageSize);
设置分页对象,创建SolrPager实体
public class SolrPager {
private int pageIndex; //当前页码
private int pageSize;//每页大小
private int pageCount;//总页数
private long recordCount;//总记录数
private List<Goods> GoodsList;//当前页数据
}
从queryResponse获取记录数返回的是一个long类型
long recordCount=queryResponse.getResults().getNumFound();
实例化SolrPager对象
//组装分页类对象
SolrPager solrPager=new SolrPager();
solrPager.setPageIndex(pageIndex);
solrPager.setPageSize(pageSize);
solrPager.setGoodsList(goodsList);
solrPager.setRecordCount(recordCount);
//总页数=总记录数/页面大小
int pageCount=(int)Math.ceil((double)recordCount/pageSize);
solrPager.setPageCount(pageCount);
前端 thymeleaf ${#numbers.sequence(1,3)}表示1到3的序列化
<th:block th:each="pageIndex:${#numbers.sequence(1,session.solrPager.pageCount)}">
<li th:if="${session.solrPager.pageIndex==pageIndex}" class="am-active"><a href="#" th:href="@{/goods/showGoodsByWhereBySolr(pageIndex=${pageIndex},cid=${session.cid})}" th:text="${pageIndex}"></a></li>
<li th:unless="${session.solrPager.pageIndex==pageIndex}"><a href="#" th:href="@{/goods/showGoodsByWhereBySolr(pageIndex=${pageIndex},cid=${session.cid})}" th:text="${pageIndex}"></a></li>
</th:block>
小结:如果从主页的搜索开始搜,此时关键字默认是空的,cid也是默认的0(无对应的商品),如果不输入文字就是查找全部,此时的cid也是空的;如果是从分类的页面进入,cid是有的,此时查找的就是cid里面有的关键字信息。将所有的索引都设置为默认的,以此易进行判断
showGoodsByWhereBySolr(@RequestParam(name="pageIndex",defaultValue = "1")int pageIndex, @RequestParam(name = "cid",defaultValue = "0") int cid, @RequestParam(name="keyword",defaultValue = "")String keyword)
<form action="search.html" th:method="get" th:action="@{/goods/showGoodsByWhereBySolr}">
<input type="hidden" name="cid" th:if="${session.cid!=null} "th:value="${session.cid}"/>
<input id="searchInput" th:if="${session.keyword!=null}" th:value="${session.keyword}" name="keyword" type="text" placeholder="搜索" autocomplete="off">
<input id="searchInput" th:if="${session.keyword==null}" name="keyword" type="text" placeholder="搜索" autocomplete="off">
<input id="ai-topsearch" class="submit am-btn" value="搜索" index="1" type="submit">
</form>