框架 day74 涛涛商城项目整合ssm,分页插件pagehelper,商品列表查询

来源:互联网 发布:中国联通音乐软件有些 编辑:程序博客网 时间:2024/05/13 19:20

讲师:入云龙


1.  课程计划

1、 SSM框架整合

2、 mybatis逆向工程

3、 商品列表

4、 商品列表分页处理

 

 

 

2.  SSM框架整合

2.1.  后台系统所用的技术

框架:Spring + SpringMVC +Mybatis

前端:EasyUI

数据库:mysql

2.2.  创建数据库

1、安装mysql数据库

2、在mysql中创建一个taotao数据库

3、导入数据库脚本。

PS:在互联网行业的项目中尽可能的减少表的管理查询。使用冗余解决表的关联问题。有利于分库分表。

Sku:最小库存量单位。就是商品id。就是商品最细力度的划分。每个sku都唯一对应一款商品,商品的颜色、配置都已经唯一确定。(例:同一款手机,不同配置)

 

2.3.  Mybatis逆向工程

执行逆向工程

使用官方网站的mapper自动生成工具mybatis-generator-core-1.3.2来生成po类和mapper映射文件。

PS:

注意:如果想再次生成代码,必须先将已经生成的代码删除,否则会在原文件中追加

 

 

 

2.4.  整合思路

1、Dao层:

mybatis整合spring,通过spring管理SqlSessionFactory、mapper代理对象。需要mybatis和spring的整合包。

使用mybatis框架。创建SqlMapConfig.xml。

创建一个applicationContext-dao.xml

1、配置数据源

2、需要让spring容器管理SqlsessionFactory,单例存在。

3、把mapper的代理对象放到spring容器中。使用扫描包的方式加载mapper的代理对象。

 

整合内容

对应工程

Pojo

Taotao-mangaer-pojo

Mapper映射文件

Taotao-mangaer-mapper

Mapper接口

Taotao-mangaer-mapper

sqlmapConfig.xml

Taotao-manager-web

applicationContext-dao.xml

Taotao-manager-web

 

2、Service层:

所有的实现类都放到spring容器中管理。由spring创建数据库连接池,并有spring管理实务。

1、事务管理

2、需要把service实现类对象放到spring容器中管理。

 

整合内容

对应工程

Service接口及实现类

Taotao-mangaer-service

applicationContext-service.xml

Taotao-manager-web

applicationContext-trans.xml

Taotao-manager-web

 

3、表现层:

Springmvc整合spring框架,由springmvc管理controller。

1、配置注解驱动

2、配置视图解析器

3、需要扫描controller

 

整合内容

对应工程

springmvc.xml

Taotao-manager-web

Controller

Taotao-manager-web

 

4、Web.xml

1、spring容器的配置

2、Springmvc前端控制器的配置

3、Post乱码过滤器

 

5、框架整合

需要把配置文件放到taotao-manager-web工程下。因为此工程为war工程,其他的工程只是一个jar包。

 

2.5.  Dao整合

2.5.1.   创建SqlMapConfig.xml配置文件

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEconfiguration

          PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

          "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

 

</configuration>

 

2.5.2.   Spring整合mybatis

创建applicationContext-dao.xml

<beansxmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"

     xmlns:aop="http://www.springframework.org/schema/aop"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-4.0.xsd

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

 

     <!-- 数据库连接池 -->

     <!-- 加载配置文件 -->

     <context:property-placeholderlocation="classpath:properties/*.properties"/>

     <!-- 数据库连接池 -->

     <beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"

          destroy-method="close">

          <propertyname="url"value="${jdbc.url}"/>

          <propertyname="username"value="${jdbc.username}"/>

          <propertyname="password"value="${jdbc.password}"/>

          <propertyname="driverClassName"value="${jdbc.driver}"/>

          <propertyname="maxActive"value="10"/>

          <propertyname="minIdle"value="5"/>

     </bean>

     <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->

     <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">

          <!-- 数据库连接池 -->

          <propertyname="dataSource"ref="dataSource"/>

          <!-- 加载mybatis的全局配置文件 -->

          <propertyname="configLocation"value="classpath:mybatis/SqlMapConfig.xml"/>

     </bean>

     <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">

          <propertyname="basePackage"value="com.taotao.mapper"/>

     </bean>

</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/taotao?characterEncoding=utf-8

jdbc.username=root

jdbc.password=root

 

 

备注:

Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。

Druid已经在阿里巴巴部署了超过600个应用,经过多年多生产环境大规模部署的严苛考验。

 

2.6.  Service整合

2.6.1.   管理Service实现类

<beansxmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"

     xmlns:aop="http://www.springframework.org/schema/aop"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-4.0.xsd

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

 

          <context:component-scanbase-package="com.taotao.service"/>

 

</beans>

 

 

2.6.2.   事务管理

创建applicationContext-trans.xml

<beansxmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"

     xmlns:aop="http://www.springframework.org/schema/aop"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-4.0.xsd

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

     <!-- 事务管理器 -->

     <beanid="transactionManager"

          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

          <!-- 数据源 -->

          <propertyname="dataSource"ref="dataSource"/>

     </bean>

     <!-- 通知 -->

     <tx:adviceid="txAdvice"transaction-manager="transactionManager">

          <tx:attributes>

               <!-- 传播行为 -->

               <tx:methodname="save*"propagation="REQUIRED"/>

               <tx:methodname="insert*"propagation="REQUIRED"/>

               <tx:methodname="add*"propagation="REQUIRED"/>

               <tx:methodname="create*"propagation="REQUIRED"/>

               <tx:methodname="delete*"propagation="REQUIRED"/>

               <tx:methodname="update*"propagation="REQUIRED"/>

               <tx:methodname="find*"propagation="SUPPORTS"read-only="true"/>

               <tx:methodname="select*"propagation="SUPPORTS"read-only="true"/>

               <tx:methodname="get*"propagation="SUPPORTS"read-only="true"/>

          </tx:attributes>

     </tx:advice>

     <!-- 切面 -->

     <aop:config>

          <aop:advisoradvice-ref="txAdvice"

               pointcut="execution(* com.taotao.service.*.*(..))"/>

     </aop:config>

</beans>

 

2.7.  表现层整合

2.7.1.   Springmvc.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 

     <context:component-scanbase-package="com.taotao.controller"/>

     <mvc:annotation-driven/>

     <bean

          class="org.springframework.web.servlet.view.InternalResourceViewResolver">

          <propertyname="prefix"value="/WEB-INF/jsp/"/>

          <propertyname="suffix"value=".jsp"/>

     </bean>

</beans>

 

2.7.2.   web.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

     id="WebApp_ID"version="2.5">

     <display-name>taotao-manager-web</display-name>

     <welcome-file-list>

          <welcome-file>login.html</welcome-file>

     </welcome-file-list>

    <!-- 加载spring容器 -->

     <context-param>

          <param-name>contextConfigLocation</param-name>

          <param-value>classpath:spring/applicationContext*.xml</param-value>

     </context-param>

     <listener>

          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

     </listener>

 

     <!-- 解决post乱码 -->

     <filter>

          <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>

          <url-pattern>/*</url-pattern>

     </filter-mapping>

 

 

     <!-- springmvc的前端控制器 -->

     <servlet>

          <servlet-name>taotao-manager</servlet-name>

          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

          <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocationspringmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->

          <init-param>

               <param-name>contextConfigLocation</param-name>

               <param-value>classpath:spring/springmvc.xml</param-value>

          </init-param>

          <load-on-startup>1</load-on-startup>

     </servlet>

     <servlet-mapping>

          <servlet-name>taotao-manager</servlet-name>

          <url-pattern>/</url-pattern>

     </servlet-mapping>

</web-app>

 

2.7.3.   整合静态页面

静态页面位置:02.第二天(三大框架整合,后台系统搭建)\01.参考资料\后台管理系统静态页面

 

使用方法:

把静态页面添加到taotao-manager-web工程中的WEB-INF下:


由于在web.xml中定义的url拦截形式为“/”表示拦截所有的url请求,包括静态资源例如css、js等。所以需要在springmvc.xml中添加资源映射标签:

     <mvc:resourceslocation="/WEB-INF/js/"mapping="/js/**"/>

     <mvc:resourceslocation="/WEB-INF/css/"mapping="/css/**"/>

 

2.8.  Springmvc和spring的父子容器关系

 

例如:

在applicationContext-service中配置:

<!-- 扫描包加载Service实现类 -->

<context:component-scanbase-package="com.taotao"></context:component-scan>

会扫描@Controller@Service@Repository@Compnent

 

SpringmvcXml中不扫描。

结论:springmvc。不能提供服务,因为springmvc子容器中没有controller对象。

 

2.9.  修改taotao-manager-mapper的pom文件


解决方法:在pom文件中添加如下内容:

<!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->

     <build>

          <resources>

            <resource>

                <directory>src/main/java</directory>

                <includes>

                    <include>**/*.properties</include>

                    <include>**/*.xml</include>

                </includes>

                <filtering>false</filtering>

            </resource>

        </resources>

     </build>

 

 

 

 

2.10.     整合测试

根据商品id查询商品信息。

 

2.10.1.         需求

跟据商品id查询商品信息。

2.10.2.         Sql语句

SELECT * from tb_item WHERE id=536563

 

2.10.3.         Dao层

可以使用逆向工程生成的mapper文件。

 

2.10.4.         Service层

接收商品id调用dao查询商品信息。返回商品pojo对象。

/**

 * 商品管理Service

 * <p>Title: ItemServiceImpl</p>

 * <p>Description:</p>

 * <p>Company: www.itcast.com</p>

 * @author    入云龙

 * @date  2015年9月2日上午10:47:14

 * @version 1.0

 */

@Service

public class ItemServiceImpl implements ItemService {

 

     @Autowired

     private TbItemMapperitemMapper;

    

     @Override

     public TbItem getItemById(longitemId) {

         

          //TbItem item = itemMapper.selectByPrimaryKey(itemId);

          //添加查询条件

          TbItemExample example = new TbItemExample();

          Criteria criteria = example.createCriteria();

          criteria.andIdEqualTo(itemId);

          List<TbItem> list = itemMapper.selectByExample(example);

          if (list !=null && list.size() > 0) {

               TbItem item = list.get(0);

               returnitem;

          }

          return null;

     }

 

}

 

2.10.5.         Controller层

接收页面请求商品id,调用service查询商品信息。直接返回一个json数据。需要使用@ResponseBody注解。

@Controller

public class ItemController {

 

     @Autowired

     private ItemServiceitemService;

    

     @RequestMapping("/item/{itemId}")

     @ResponseBody

     public TbItem getItemById(@PathVariable Long itemId) {

          TbItem tbItem = itemService.getItemById(itemId);

          returntbItem;

     }

}

 

2.11.     使用maven的tomcat插件时debug

第一次debug会出现如图情形


点击上图 Edit Source lookupPath..


下次启动生效。

 

第二种方法:


3.  商品列表查询

 

3.1.  打开后台管理工程的首页

分析:先写一个controller进行页面跳转展示首页。

首页是使用easyUI开发。

 

 

/**

 * 页面跳转controller

 * <p>Title: PageController</p>

 * <p>Description:</p>

 * <p>Company: www.itcast.com</p>

 * @author    入云龙

 * @date  2015年9月2日上午11:11:41

 * @version 1.0

 */

@Controller

public class PageController {

 

     /**

      * 打开首页

      */

     @RequestMapping("/")

     public String showIndex() {

          return"index";

     }

     /**

      * 展示其他页面

      * <p>Title:showpage</p>

      * <p>Description:</p>

      * @param page

      * @return

      */

     @RequestMapping("/{page}")

     public String showpage(@PathVariable Stringpage) {

          returnpage;

     }

}

 

 

 

 

3.2.  商品列表页面


对应的jsp为

item-list.jsp

 

请求的url:

/item/list

请求的参数:

page=1&rows=30

响应的json数据格式:

Easyui中datagrid控件要求的数据格式为:

{total:”2”,rows:[{“id”:”1”,”name”,”张三”},{“id”:”2”,”name”,”李四”}]}


3.3.  响应的json数据格式EasyUIResult

public class EasyUIResult {

 

    private Integertotal;

 

    private List<?>rows;

 

    public EasyUIResult(Integertotal, List<?> rows) {

        this.total =total;

        this.rows =rows;

    }

 

    public EasyUIResult(Longtotal, List<?> rows) {

        this.total =total.intValue();

        this.rows =rows;

    }

 

    public Integer getTotal() {

        returntotal;

    }

 

    public void setTotal(Integer total) {

        this.total =total;

    }

 

    public List<?> getRows() {

        returnrows;

    }

 

    public void setRows(List<?> rows) {

        this.rows =rows;

    }

 

}

 

3.4.  分页处理

3.4.1.   Mybatis分页插件 -PageHelper说明

如果你也在用Mybatis,建议尝试该分页插件,这个一定是最方便使用的分页插件。

该插件目前支持Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库分页。

:https://github.com/pagehelper/Mybatis-PageHelper/tree/master/src/main/java/com/github/pagehelper

原理:

 

3.4.2.   使用方法

第一步:在Mybatis配置SqlMapConfig.xml中配置拦截器插件:

<plugins>

   <!-- com.github.pagehelperPageHelper类所在包名 -->

   <plugininterceptor="com.github.pagehelper.PageHelper">

       <!--设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->       

       <propertyname="dialect"value="mysql"/>

   </plugin>

</plugins>

第二步:在代码中使用

1、设置分页信息:

    //获取第1页,10条内容,默认查询总数count

   PageHelper.startPage(1,10);

 

   //紧跟着的第一个select方法会被分页

List<Country> list= countryMapper.selectIf(1);

2、取分页信息

//分页后,实际返回的结果list类型是Page<E>,如果想取出分页信息,需要强制转换为Page<E>

Page<Country>listCountry = (Page<Country>)list;

listCountry.getTotal();

3、取分页信息的第二种方法

//获取第1页,10条内容,默认查询总数count

PageHelper.startPage(1,10);

List<Country> list= countryMapper.selectAll();

//PageInfo对结果进行包装

PageInfo page=new PageInfo(list);

//测试PageInfo全部属性

//PageInfo包含了非常全面的分页属性

assertEquals(1, page.getPageNum());

assertEquals(10, page.getPageSize());

assertEquals(1, page.getStartRow());

assertEquals(10, page.getEndRow());

assertEquals(183, page.getTotal());

assertEquals(19, page.getPages());

assertEquals(1, page.getFirstPage());

assertEquals(8, page.getLastPage());

assertEquals(true, page.isFirstPage());

assertEquals(false, page.isLastPage());

assertEquals(false, page.isHasPreviousPage());

assertEquals(true, page.isHasNextPage());

 

分页测试

public class TestPageHelper {

 

     @Test

     public void testPageHelper() {

          //创建一个spring容器

          ApplicationContext applicationContext =new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");

          //从spring容器中获得Mapper的代理对象

          TbItemMapper mapper =applicationContext.getBean(TbItemMapper.class);

          //执行查询,并分页

          TbItemExample example =new TbItemExample();

          //分页处理

          PageHelper.startPage(2, 10);

          List<TbItem> list = mapper.selectByExample(example);

          //取商品列表

          for (TbItemtbItem : list) {

               System.out.println(tbItem.getTitle());

          }

          //取分页信息

          PageInfo<TbItem> pageInfo = new PageInfo<>(list);

          longtotal = pageInfo.getTotal();

          System.out.println("共有商品:"+total);

         

     }

}

 

 

注意:分页插件对逆向工程生成的代码支持不好,不能对有查询条件的查询分页。会抛异常。

需要使用-fix版本

3.5.  Mapper

使用逆向工程生成的mapper文件。

 

3.6.  Service

接收分页参数,一个是page一个是rows。调用dao查询商品列表。并分页。返回商品列表。

返回一个EasyUIDateGrid支持的数据格式。需要创建一个Pojo。此pojo应该放到taotao-common工程中。

 

@Service

public class ItemServiceImpl implements ItemService {

 

     @Autowired

     private TbItemMapperitemMapper;

     @Override

     public EasyUIResult getItemList(Integer page, Integerrows) throws Exception {

          TbItemExample example =new TbItemExample();

          //设置分页

          PageHelper.startPage(page,rows);

          List<TbItem> list = itemMapper.selectByExample(example);

          //取分页信息

          PageInfo<TbItem> pageInfo =new PageInfo<>(list);

          longtotal = pageInfo.getTotal();

          EasyUIResult result =new EasyUIResult(total,list);

         

          returnresult;

     }

 

}

 

3.7.  Controller

接收页面传递过来的参数page、rows。返回json格式的数据。EUDataGridResult

需要使用到@ResponseBody注解。

 

@Controller

@RequestMapping("/item")

public class ItemController {

    

     @Autowired

     private ItemServiceitemService;

 

     @RequestMapping("/list")

     //设置相应的内容为json数据

     @ResponseBody

     public EasyUIResult getItemlist(@RequestParam(defaultValue="1")Integerpage,

               @RequestParam(defaultValue="30")Integerrows) throws Exception {

          //查询商品列表

          EasyUIResult result =itemService.getItemList(page,rows);

         

          returnresult;

     }

}

 

 效果


 

 

 

 

 

 

 

 

 

 

 

 

0 0
原创粉丝点击