1. 程式人生 > >Spring(1)之 (1.4_Spring WEB)Web 專案中使用 Spring

Spring(1)之 (1.4_Spring WEB)Web 專案中使用 Spring

1. Spring負責物件的建立( 控制反轉 IOC),處理物件之間的依賴關係(依賴注入 DI)

2. Spring在 WEB應用中的使用:整合Mybatis、Hibernate、SpringMVC、Struts

3. 使用步驟:

  1. 引入 jar包:
    spring-core
    spring-web:spring-web-4.x.jar、spring-webmvc-4.x.jar
    在這裡插入圖片描述
  2. 配置檔案
    bean.xml(/applicationContext.xml)—spring容器的配置
    web.xml—初始化 springIOC容器

eg_專案工程目錄:

在這裡插入圖片描述


1. bean.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- base-package掃描包即子包下的類 -->
    <context:component-scan base-package="com.asd"></context:component-scan>
    
</beans>

2. web.xml
(參考 tomcat安裝目錄下的 webapps/examples/WEB-INF/web.xml ;此web.xml檔案中: < welcome-file-list> 標籤配置預設請求的頁面;因為此 web.xml檔案是被應用程式預設載入的,所以在此檔案中配置SpringIOC容器載入:通過< listener>標籤配置容器的上下文載入,通過 < context-param> 標籤載入相應的 xml檔案(因為編譯後的 xml檔案是 WEB-INF下的 classes資料夾下,所以路徑寫classes;bean*表示以 bean開頭的多個 bean檔案; ))

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
  version="3.0">
  
  <!-- 配置SpringIOC容器載入 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>/WEB-INF/classes/bean*.xml</param-value>//
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <welcome-file-list><!-- 預設請求的頁面 -->
        <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

3. UserDao.java

@Repository  //持久層
public class UserDao{
	public void save(){
		System.out.println("儲存到資料庫");
	}
}

4. UserService.java

@Service  //業務邏輯層
public class UserService{
	@Resource
	private UserDao userDao;
	public void save(){
		userDao.save();
	}
}

5. UserAction.java

@Controller //控制層
public class UserAction{
        @Resource
	private UserSerice userService;
	public String addUser(){
		userService.save();
		return null;
	}
}

執行結果:(jsp頁面顯示的內容)