SpringMvc整合mybatis和簡單參數綁定

通過對SpringMvc的入門程序簡單的學習,接下來就學習SpringMvc整合mybatis。
整合目標:控制層採用springmvc、持久層使用mybatis實現。
實現商品查詢列表,從mysql數據庫查詢商品信息。

1.jar包

包括:spring(包括springmvc)、mybatis、mybatis-spring整合包、數據庫驅動、第三方連接池。
這裏寫圖片描述

這裏寫圖片描述

2.ssm整合思路

1.Dao層
pojo和映射文件以及接口使用逆向工程生成
SqlMapConfig.xml 和 mybatis核心配置文件
ApplicationContext-dao.xml 整合後spring在dao層的配置,包括:數據源、會話工廠、掃描Mapper
2. service層
事務:ApplicationContext-trans.xml
@Service註解掃描:ApplicationContext-service.xml
3. controller層
SpringMvc.xml
註解掃描:掃描@Controller註解
註解驅動:替我們顯示的配置了最新版的處理器映射器和處理器適配器
視圖解析器:顯示的配置是爲了在controller中不用每個方法都寫頁面的全路徑
4. web.xml
springMvc:前端控制器配置
spring監聽

配置文件

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>

</configuration>

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: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-placeholder location="classpath:db.properties" />
    <!-- 數據庫連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 整合後會話工廠歸spring管理 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis核心配置文件 
            spring配置:要加classpath
        -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
        <!-- 指定會話工廠使用的數據源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置原生Dao實現   class必須指定dao實現類的全路徑名 -->
    <bean id="userDao" class="com.dml.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>


    <!-- mapper接口代理的實現 -->
    <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        配置mapper接口的全路徑名稱
        <property name="mapperInterface" value="com.dml.mapper.UserMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean> -->

    <!-- 使用包掃描的方式批量引入Mapper
        掃描後引用的時候可以使用類名,首字母小寫.
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定要掃描的包全路徑名稱,如果有多個包用英文狀態下的逗號分隔 -->
        <property name="basePackage" value="com.dml.mapper"></property>
    </bean>
</beans>

注意修改自己的dao配置路徑和掃描包的包名
這裏的db.properties文件請參照Mybatis整合spring
文章中的配置,注意修改數據庫的用戶名和密碼

ApplicationContext-service.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: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">

    <!-- @Service掃描 -->
    <context:component-scan base-package="com.dml.service"></context:component-scan>
</beans>

這裏注意修改掃描包的包名
ApplicationContext-trans.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: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">

    <!-- 事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 數據源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 傳播行爲 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.dml.service.*.*(..))" />
    </aop:config>

</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:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- @Controller註解掃描 -->
    <context:component-scan base-package="com.dml.controller"></context:component-scan>

    <!-- 註解驅動:
            替我們顯示的配置了最新版的註解的處理器映射器和處理器適配器 -->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

    <!-- 配置視圖解析器 
    作用:在controller中指定頁面路徑的時候就不用寫頁面的完整路徑名稱了,可以直接寫頁面去掉擴展名的名稱
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 真正的頁面路徑 =  前綴 + 去掉後綴名的頁面名稱 + 後綴 -->
        <!-- 前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 後綴 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置自定義轉換器 
    注意: 一定要將自定義的轉換器配置到註解驅動上
    -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <!-- 指定自定義轉換器的全路徑名稱 -->
                <bean class="com.dml.controller.converter.CustomGlobalStrToDateConverter"/>
            </set>
        </property>
    </bean>

</beans>

注意修改掃描的包名和自定義轉換器的全路徑名
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 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>ssm</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <!-- 加載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>

  <!-- springmvc前端控制器 -->
  <servlet>
    <servlet-name>springMvc</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>
    <!-- 在tomact啓動的時候加載這個servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

  <!-- 配置過濾器解決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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

ItemsServiceImpl.java

@Service
public class ItemsServiceImpl implements ItemsService{
    @Autowired
    private ItemsMapper itemsMapper;

    //查詢列表,全部的數據
    @Override
    public List<Items> list() throws Exception {
        //如果不需要任何查詢條件,直接將ItemsExample對象new出來即可
        ItemsExample example = new ItemsExample();
        List<Items> list = itemsMapper.selectByExampleWithBLOBs(example);

        return list;
    }

    //通過id查詢商品對象
    @Override
    public Items findItemsById(Integer id) throws Exception {
        Items items = itemsMapper.selectByPrimaryKey(id);
        return items;
    }

    //更新商品信息
    @Override
    public void updateitem(Items items) throws Exception {
        itemsMapper.updateByPrimaryKeyWithBLOBs(items);
    }
}

ItemsController.java

@Controller
public class ItemsController {
    //@Autowired自動注入,但是有多個實現類時就不知道注入哪個了

//  @Resource(name="itemsService")
    @Autowired
    private ItemsService itemsService;

    //指定url到請求方法的映射
    //url中輸入一個地址,找到這個方法,例如:localhost:8080/springmvc/list.action
    @RequestMapping("/list")
    public ModelAndView itemsList() throws Exception{
        //調用service查詢列表
        List<Items> itemList = itemsService.list();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList",itemList);

        //設置頁面路徑
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

    /**
     * 通過id查詢商品對象
     * springmvc中默認支持的參數類型:也就是說在controller方法中可以加入這些,也可以不加
     * HttpServletRequest
     * HttpServletResponse
     * HttpSession
     * Model
     */
    @RequestMapping("/itemEdit")
    public String itemEdit(HttpServletRequest request,HttpServletResponse response,
            HttpSession session,Model model) throws Exception{
        String idStr = request.getParameter("id");
        Integer id = Integer.parseInt(idStr);
        Items items = itemsService.findItemsById(id);

        //Model模型:模型中放入了返回給頁面的數據
        //Model底層其實就是用的request域來傳遞數據,但是對request域進行了擴展
        model.addAttribute("item",items);

        //如果springmvc方法返回一個簡單的string字符串,那麼springmvc就會認爲這個字符串就是頁面的名稱
        return "editItem";
    }

    //更新商品信息
    //springmvc可以直接接收基本數據類型,包括string,springmvc可以幫你自動進行類型轉換
    //controller方法接收的參數的變量名稱必須要等於頁面上input框的name屬性值
    //  public String update(Integer id,String name,Float price,String detail) throws Exception{

    //springmvc可以直接接收pojo類型:要求頁面上input框的name屬性名稱必須等於pojo屬性名稱
    @RequestMapping("/updateitem")
    public String update(Items items) throws Exception{
//      items.setCreatetime(new Date());

        itemsService.updateitem(items);
        return "success";
    }


    //高級查詢
    //如果Controller中接收的是Vo,那麼頁面上input框的name屬性值要等於vo的屬性.屬性.屬性
    @RequestMapping("/search")
    public String search(QueryVo vo) throws Exception{

        System.out.println(vo);
        return "success";
    }
}

pojo和映射文件以及接口使用逆向工程生成,關於逆向工程
總結的很亂,想每天總結自己學習的內容,但是發現還是沒有辦法做到,東西多,很多也只是複製粘貼了老師的。總之還在努力吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章