Spring+Mybatis整合案例電商模塊

框架整合

  • 導入項目的配置依賴到pom.xml文件中
  • 項目分層,創建實體類,創建Mybatis的持久層接口及映射文件
  • 配置Spring框架配置文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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>com.imooc</groupId>
  <artifactId>Mybatis-Spring</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Mybatis-Spring Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://maven.apache.org</url>

  <properties>
    <junit.version>4.11</junit.version>
    <jsp.api.version>8.5.5</jsp.api.version>
    <jstl.version>1.2</jstl.version>
    <spring.version>4.1.6.RELEASE</spring.version>
    <aspectjweaver.version>1.8.5</aspectjweaver.version>
    <mybatis.version>3.2.8</mybatis.version>
    <mybatis.spring.version>1.2.2</mybatis.spring.version>
    <c3p0.version>0.9.5</c3p0.version>
    <mysql.version>5.1.35</mysql.version>
    <log4j.version>1.2.17</log4j.version>
    <json.version>2.4</json.version>
  </properties>


  <dependencies>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <!-- 該jar包保留到測試 -->
      <scope>test</scope>
    </dependency>
    <!-- jsp-api、servlet-api、el -->
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-jsp-api</artifactId>
      <version>${jsp.api.version}</version>
      <!-- 該jar包最終由Web容器提供 -->
      <scope>provided</scope>
    </dependency>

    <!-- jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <!-- Spring4 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
      <exclusions>
        <exclusion>
          <artifactId>commons-logging</artifactId>
          <groupId>commons-logging</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectjweaver.version}</version>
    </dependency>
    <!-- mybatis3 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>${c3p0.version}</version>
    </dependency>
    <!-- mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <!-- json-lib -->
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>${json.version}</version>
      <!-- 指定jar包jdk版本的依賴 -->
      <classifier>jdk15</classifier>
      <exclusions>
        <exclusion>
          <artifactId>commons-lang</artifactId>
          <groupId>commons-lang</groupId>
        </exclusion>
      </exclusions>
    </dependency>

  </dependencies>

  <build>
    <finalName>Mybatis-Spring</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

ec_article

ec_article_type

ec_user

創建實體類和映射文件

配置Spring框架配置文件

<?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:c="http://www.springframework.org/schema/c"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      				  http://www.springframework.org/schema/beans/spring-beans-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/context
      				  http://www.springframework.org/schema/context/spring-context-4.0.xsd
      				  ">

    <!-- 聲明用了annotation註解bean
           開啓組件掃描:它會到基礎包下掃描@Service @Repository @Controller @Component這四種註解聲明的bean,
          掃描後會將這些bean交由Spring容器管理
    -->
    <context:component-scan base-package="com.imooc.shop"></context:component-scan>

    <!-- 配置數據源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"/>

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource">
        <!-- 配置類型別名:採用包掃描的方式到基礎包下掃描所有的類,作爲MyBatis2能夠轉換的類型,多個包之間用;分隔 -->
        <property name="typeAliasesPackage">
            <value>
                com.imooc.shop.bean
            </value>
        </property>
    </bean>

    <!-- 配置數據訪問接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:sqlSessionFactoryBeanName="sqlSessionFactory">
        <!-- 配置數據訪問接口:採用包掃描的方式到基礎包下掃描所有的類,作爲MyBatis2的數據訪問接口,
            並創建這些類的代理對象,創建出來後會把這些代理對象交給Spring容器管理,bean的id名默認爲接口的類名前面首字母小寫
           多個包之間用;分隔 -->
        <property name="basePackage">
            <value>
                com.imooc.shop.repository
            </value>
        </property>
    </bean>

    <!-- 配置DataSourceTransactionManager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

    <!-- 開啓annotation註解事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

c3p0.properties

架構串聯測試

書寫一個查詢所有商品類型的Servlet類

在Servlet中注入業務層組件

調用業務層組件的方法

在業務層組件中注入Mybatis的持久層對象

在持久層對象中查詢出所有商品類型數據返回

package com.imooc.shop.action;

import com.imooc.shop.bean.ArticleType;
import com.imooc.shop.service.ShopService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/getArticleTypes")
public class ArticleTypeServlet extends HttpServlet {
    //定義業務層對象
    private ShopService shopService;

    @Override
    public void init() throws ServletException {
        super.init();
        //獲取Spring容器,然後從容器中得到業務層對象
        ServletContext servletContext =this.getServletContext();
        WebApplicationContext context =
                WebApplicationContextUtils.getWebApplicationContext(servletContext);
        shopService = (ShopService)context.getBean("shopService");


    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查詢出所有的商品類型信息
        List<ArticleType> articleTypes = shopService.getArticleTypes();
        System.out.println(articleTypes);
    }
}

ShopService

package com.imooc.shop.service;


import com.imooc.shop.bean.ArticleType;

import java.util.List;

public interface ShopService {
    List<ArticleType> getArticleTypes();

}

shopServiceImpl

package com.imooc.shop.service;

import com.imooc.shop.bean.ArticleType;
import com.imooc.shop.repository.ArticleTypeMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("shopService")
public class ShopServiceImpl implements ShopService {
    //得到數據訪問層對象
    @Resource
    private ArticleTypeMapper articleTypeMapper;

    @Override
    public List<ArticleType> getArticleTypes() {
        return articleTypeMapper.getArticleTypes();
    }
}

ArticleTypeMapper

package com.imooc.shop.repository;

import com.imooc.shop.bean.ArticleType;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface ArticleTypeMapper {

    @Select("select * from ec_article_type")
    List<ArticleType> getArticleTypes();
}

整合成功 

用戶登錄

導入界面架構

LoginServlet.java

package com.imooc.shop.action;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,resp);
    }
}

index.jsp 

完成登錄

LoginServlet

package com.imooc.shop.action;

import com.imooc.shop.bean.User;
import com.imooc.shop.service.ShopService;
import com.imooc.shop.utils.Constants;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private HttpServletRequest request;
    private HttpServletResponse response;
    //定義業務層對象
    private ShopService shopService;
    @Override
    public void init() throws ServletException {
        super.init();
        //獲取spring的容器,然後從容器中得到業務層對象
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext context =
                WebApplicationContextUtils.getWebApplicationContext(servletContext);
        shopService = (ShopService)context.getBean("shopService");

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.request=req;
        this.response=resp;
        String method = req.getParameter("method");
        switch (method) {
            case "getJsp":
                //跳轉到登錄界面
                req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
                break;
            case "login":
                login();
                break;
        }
    }

    private void login(){
        try {
            String loginName= request.getParameter("loginName");
            String passWord = request.getParameter("passWord");
            Map<String,Object> results = shopService.login(loginName,passWord);
            if((int)results.get("code")==0) {
                //登錄成功的
                //把登錄成功的用戶注入到session會話中去
                //跳轉到主頁面
                User user = (User) results.get("msg");
                request.setAttribute(Constants.USER_SESSION,user);
                //請求跳轉到主界面的servlet
                request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);

            }else{
                String msg = results.get("msg")+"";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

ShopService

package com.imooc.shop.service;


import com.imooc.shop.bean.ArticleType;

import java.util.List;
import java.util.Map;

public interface ShopService {
    List<ArticleType> getArticleTypes();
    Map<String,Object> login(String loginName, String passWord);
}

ShopServiceImpl

package com.imooc.shop.service;

import com.imooc.shop.bean.ArticleType;
import com.imooc.shop.bean.User;
import com.imooc.shop.repository.ArticleTypeMapper;
import com.imooc.shop.repository.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("shopService")
public class ShopServiceImpl implements ShopService {
    //得到數據訪問層對象
    @Resource
    private ArticleTypeMapper articleTypeMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public List<ArticleType> getArticleTypes() {
        return articleTypeMapper.getArticleTypes();
    }

    @Override
    public Map<String, Object> login(String loginName, String passWord) {
       Map<String,Object> results = new HashMap<>();
       //判斷參數是否爲空的
        if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(passWord)){
            //參數爲空了
            results.put("code",1);
            results.put("msg","參數爲空了");
        }else{
            //根據登錄名稱去查詢用戶對象
            User user =userMapper.login(loginName);
            System.out.println(user.getPassword());
            if(user !=null){
                //判斷密碼
                if(user.getPassword().equals(passWord)){
                    //登錄成功了
                    //應該將登陸成功的用戶存到Session會話中
                    results.put("code",0);
                    results.put("msg",user);

                }else{
                    //密碼錯誤了
                    results.put("code",2);
                    results.put("msg","密碼錯誤了");
                }
            }else{
                //登錄名不存在
                results.put("code",3);
                results.put("msg","登錄名不存在");
            }

        }
        return results;
    }
}

UserMapper 

package com.imooc.shop.repository;

import com.imooc.shop.bean.User;
import org.apache.ibatis.annotations.Select;


public interface UserMapper {

    @Select("select * from ec_user where login_name=#{xxx}")
    User login(String loginName);

}

util.Constants

package com.imooc.shop.utils;

public class Constants {
    public static final String USER_SESSION="user_session";
}

 

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