1. 程式人生 > >JavaWeb學習之路——SSM框架之Spring(五)

JavaWeb學習之路——SSM框架之Spring(五)

                                        整合Spring和Mybatis框架

1.在專案的lib下匯入如下jar包

匯入mybatis所有jar和spring的jar基本包,spring-jdbc,spring-tx,spring-aop,spring整合mybatis等

2.編寫spring配置檔案applicationContext

在jar包下找到對應的類檔案,複製它的類名,將之加入到對應的bean的Class屬性中,下圖為一個示例:

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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

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

    <!-- id表示獲取到物件標識

      class 建立哪個類的物件

     -->

     <!-- 資料來源封裝類,相當於mybatis的environment標籤,資料類在spring-jdbc包中 -->

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

     <property name="url" value="jdbc:mysql://localhost:3306/likui"/>

     <property name="username" value="root"/>

     <property name="password" value="123456"/>

   </bean>

   <!-- 在mybatis-spring包中 -->

   <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">

   <property name="dataSource" ref="dataSource"></property>

   </bean>

  

   <!-- 掃描器,相當於mybatis下的mappers package標籤 -->

   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

   <property name="basePackage" value="com.likui.mapper"></property>

   <!-- 讓factory與資料庫相關聯 -->

   <property name="sqlSessionFactory" ref="factory"></property>

   </bean>

</beans>

對應類:MapperScannerConfigurer->SqlSessionFactoryBean->DriverManagerDataSource,層層巢狀

3.使用流程

src下程式碼結構圖:

1)在src下建立mapper包,裡面是sql語句的使用方法

public interface FlowerMapper {

     @Select("select * from flower")

     List<Flower> selAll();

}

2)在src下建立pojo包,裡面是類的構造方法和setter、getter方法,用來封裝物件

public class Flower {

     private int id;
     private String name;
     private double price;
     private String production;
     public void setList(List<Integer> list) {
           this.list = list;
     }

     public Flower(int id, String name, double price, String production) {
           this.id = id;
           this.name = name;
           this.price = price;
           this.production = production;

     }

     public Flower() {}

     public int getId() {
           return id;
     }

     public void setId(int id) {
           this.id = id;
     }

     public String getName() {
           return name;
     }

     public void setName(String name) {
           this.name = name;
     }

     public double getPrice() {
           return price;
     }

     public void setPrice(double price) {
           this.price = price;
     }

     public String getProduction() {
           return production;
     }

     public void setProduction(String production) {
           this.production = production;
     }

3)建立service包,裡面是工程專案的實現類,介面和它的實現類都放這裡面

(1)介面

public interface FlowerService {

     List<Flower> show() throws IOException ;  //顯示

}

(2)實現類

public class FlowerServiceImpl implements FlowerService{

     private FlowerMapper flowermapper;

     public FlowerMapper getFlowermapper() {

           return flowermapper;

     }

     public void setFlowermapper(FlowerMapper flowermapper) {

           this.flowermapper = flowermapper;

     }

     @Override

     public List<Flower> show() throws IOException {

           // TODO Auto-generated method stub

           return flowermapper.selAll();

     } 

}

4)在Spring的beans.xml中建立類的物件

注意對應的首字母為大寫的類或介面在引用時需要將首字母小寫,介面不能建立bean,因為不能例項化

<bean id="flowerService" class="com.likui.service.FlowerServiceImpl">

   <property name="flowermapper" ref="flowerMapper"></property>

   </bean>

5)編寫Test主函式來實現,在java檔案中利用Spring IoC獲取相應類物件

public class Test {

     public static void main(String[] args) throws IOException {

           // TODO Auto-generated method stub

           ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");

           //獲取所有spring管理的bean的名稱

           //String []names=ac.getBeanDefinitionNames();

           //for(String string:names) {

           //   System.out.println(string);

           //}

          FlowerServiceImpl flowerServiceImpl=ac.getBean("flowerService",FlowerServiceImpl.class);

          List<Flower> list=flowerServiceImpl.show();

          System.out.println("id\t\tname\t\tprice\t\tproduction");

                for (Flower flower : list) {

                System.out.println(flower.getId()+"\t\t"+flower.getName()+"\t\t"+

                flower.getPrice()+"\t\t"+flower.getProduction());

           }

     }

}

6)實驗結果展示:

4.釋出到Web專案上

因為Spring不能管理serverlet,需要用tomcat來管理它,利用tomcat提供的方法來支援Spring

1)在WEB-INF下新建web.xml配置檔案。用於載入Spring的配置檔案,獲取到相應的contextConfigLocation

程式碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

     <!-- 上下文引數 -->

     <context-param>

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

           <!-- spring配置檔案 -->

           <param-value>classpath:beans.xml</param-value>

     </context-param>

     <!-- 封裝了一個監聽器,幫助載入Spring的配置檔案 -->

     <listener>

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

     </listener>

</web-app>

2)在src下新建serverlet包,裡面寫相應的serverlet實現方法

利用init初始化方法來例項化service中介面實現類,程式碼如下:

@WebServlet("/show")

public class ShowServerlet extends HttpServlet{

     private FlowerService flowerservice;

     @Override

     public void init() throws ServletException {

           // TODO Auto-generated method stub

           //對service例項化

           //ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");

           //Spring不能管理serverlet物件,需要用tomacat來管理它,會封裝它

          ApplicationContex ac=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

          flowerservice=ac.getBean("flowerService",FlowerServiceImpl.class);

     }

     @Override

     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

           // TODO Auto-generated method stub

           req.setAttribute("list", flowerservice.show());

           req.getRequestDispatcher("/index.jsp").forward(req, resp);

     }

}

3)在WebContent下新建index.jsp用於測試。

程式碼如下所示:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

hello world!

<table>

<tr>

<th>編號</th>

<th>名字</th>

<th>價格</th>

<th>產處</th>

</tr>

     <c:forEach items="${list }" var="peo">

           <tr>

            <td>${peo.id }</td>

            <td>${peo.name }</td>

            <td>${peo.price }</td>

            <td>${peo.production }</td>

           </tr>

     </c:forEach>

</table>

</body>

</html>

4)實驗結果: