struts2環境搭建---【小白系列】0基礎到熟練應用struts2框架(一)

LawsonJin發表於2017-07-03

前記:

        其實一直很反感社會上流傳的從入門到精通,這個概念,什麼是精通?不是用過一點時間,再把原始碼看透,怎麼敢說精通。好了閒話不扯,本系列教程主要講解struts2的入門到熟練使用,同樣也是我個人學習筆記,以及我對struts2的理解

Struts2概念

         Struts2是一個基於MVC設計模式的Web應用框架,它本質上相當於一個servlet,在MVC設計模式中,Struts2作為控制器(Controller)來建立模型與檢視的資料互動。Struts 2是Struts的下一代產品,是在 struts 1和WebWork的技術基礎上進行了合併的全新的Struts 2框架。其全新的Struts 2的體系結構與Struts 1的體系結構差別巨大。Struts 2以WebWork為核心,採用攔截器的機制來處理使用者的請求,這樣的設計也使得業務邏輯控制器能夠與ServletAPI完全脫離開,所以Struts 2可以理解為WebWork的更新產品。雖然從Struts 1到Struts 2有著太大的變化,但是相對於WebWork,Struts 2的變化很小

       以上是百度百科給我們的答案,那麼我自己的理解就是Strurs是一款web表現層的框架,它採用了mvc的設計模式。常見的javaweb .net php python等等 不過作為我們的JavaEE攻城獅來說是輕mvc重三層架構的三層架構(web service dao)這是我們javaweb特有的。其實struts2和struts1關係不大,因為它是在WebWork的基礎上二次開發。你也可以理解成java和JavaScript,只是借用個名頭而已所以 struts2是WebWork的升級版 Struts2基於WebWork,而WebWork 又基於xwork

Struts2快速入門

     其實struts2就是插拔式的一個框架,所謂的插拔式就是,你想用就用,不想用了就扔掉,很方便。通俗點就是在web.xml中配一個過濾器,讓每一次請求都去走這個過濾器。
加上過濾器就算使用struts2,不加就不用了。

執行流程:

客戶端傳送請求

tomcat伺服器解析請求並且將請求資料封裝到request

然後通過過濾器,找到struts.xml中的與請求相對的action

執行action方法,返回結果


環境搭建

1.匯入struts2所需jar包

\struts2下載\struts-2.3.24-all\struts-2.3.24\apps\struts2-blank\WEB-INF\lib下所有包



\資料\其他jar包\hibernate基本jar

2.在web.xml配置過濾器

    <filter>
  	<filter-name>Struts</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>Struts</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>



3.建立Action









public class QuickTestAction {
	public void execute() {
		System.out.println("Test action .... ");
	}
	public String save(){
		return "save";
	}
	public String update(){
		return "update";
	}
	public String delete(){
		return "delete";
	}
}


4.在src下建立struts.xml


5.配置struts.xml

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<package name="mytest" extends="struts-default" namespace="/">
		<action name="test" class="com.test.struts.QuickTestAction"></action>
	</package>
</struts>

我們來訪問測試下
http://localhost:8080/strutsTest/test

如果控制檯成功輸出則struts2配置完成。

struts2核心過濾器詳解

StrutsPrepareAndExecuteFilter(Struts準備和執行過濾器)
進入這個Filter然後依次檢視實現
 dispatcher = init.initDispatcher(config);//檢視實現
 dispatcher.init();//檢視實現



伺服器在啟動時,建立filter物件,就會執行init()方法,然後載入配置檔案

載入順序:

default.properties:struts2自己定義好的配置檔案
struts-default.xml:struts2自己定義好的配置檔案
struts-plugin:struts2外掛自己定義好的配置檔案
struts.xml:自定義的
struts.properties:自定義
核心filter初始化引數:自定義

後載入的配置檔案如果與先載入的配置檔案有衝突的話,後覆蓋前

詳解配置檔案

default.properties

位置:struts-core.jar/org/apach/struts2/default.properties
該檔案內部配置的是一些常量引數 格式鍵值對
struts.i18n.encoding=UTF-8 預設編碼
post的亂碼struts2已經解決 get需要手動解決


struts.objectFactory = spring
指定Action是由哪個框架建立的 這句話的意思是把action的建立許可權交給spring


struts.devMode = false
develope mode 是否設定為開發模式
如果設定為true 變成開發模式 當修改struts.xml配置檔案後不需要重啟服務


struts.action.extension=action,,
Action訪問時的預設副檔名 例如 abc,,def,那麼(*.abc ) ( *) (*.def)可以訪問到資源


struts.multipart.maxSize=2097152
使用struts2進行檔案上傳預設的 允許上傳檔案大小


struts-default.xml

位置:struts-core.jar下
1)功能bean
2)常量
3)抽象包
4)結果跳轉型別
5)攔截器

在自己的xml配置檔案中覆蓋struts-default包內部的預設配置


struts.xml配置(包括action的配置)

在src下建立struts.xml--自定義 配置自己的內容 配置覆蓋之前檔案內容


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<!-- 根標籤 -->
<struts>
	<!-- 常量  鍵值對 -->
	<constant name="struts.devMode" value="true"></constant>
	<constant name="struts.action.extension" value="action,abc,def,,"></constant>
	<!-- 動態方法呼叫的開啟 -->
	<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
	
	<!-- package包配置 包內部配置action
			package包是一個虛擬包/邏輯包  不存在  主要目的方便action的管理
			屬性:
				name:包的名稱  包名稱不能重複
				namespace:名稱空間  該名稱空間與Action的name一起組成訪問的虛擬地址
					例如: namespace="/customer"
					url:http://localhost:8080/Struts2_Day01/customer/quick.action
				extends:該包繼承哪個包  一般情況下 繼承struts-default
					繼承了包 才能使用父包中都已經定義好的一些內容
				abstract:宣告該包是否是一個抽象包  只能被別的包繼承 不能建立Action
	 -->
	<package name="test" namespace="/" extends="struts-default">
	
		<!-- <interceptors>
			宣告自己定義的攔截器
			<interceptor name="myInterceptor" class="全包名"></interceptor>
			定義攔截器棧
			<interceptor-stack name="myStack">
				<interceptor-ref name="myInterceptor"></interceptor-ref>
				<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
		引用預設的攔截器棧
		<default-interceptor-ref name="myStack" /> -->
		
		<!-- 定義自己的結果型別 -->
		<!-- <result-types>
			<result-type name="myResultType" class="com.opensymphony.xwork2.ActionChainResult"/>
		</result-types> -->
		
		<!-- 定義Action:封裝邏輯程式碼的類
				屬性:
					name:該Action的虛擬名稱  該name與namespace一起組成訪問的虛擬的地址
					class:該Action全限定名
					method:指定訪問該Action中的哪個方法
		 -->
		<action name="quick" class="cn.nanjin.action.QuickAction" method="save">
			<!-- 結果檢視 
					屬性:
						name:邏輯檢視名
						result標籤體中配置實際的頁面的地址
						type: 跳轉方式  轉發 重定向..
			-->
			<result name="success">/success.jsp</result>
			<result name="save">/save.jsp</result>
			<result name="update">/update.jsp</result>
		</action>
		<action name="update" class="cn.nanjin.action.QuickAction" method="update">
			<result name="success">/success.jsp</result>
			<result name="save">/save.jsp</result>
			<result name="update">/update.jsp</result>
		</action>
		
		<!-- 
			*代表任意 標識萬用字元
			{n} n代表第幾個*
			
			例如:
				http://localhost:8080/Struts2_Day01/quick2_save.action
				*===save
				method="save"
				
				http://localhost:8080/Struts2_Day01/quick2_update.action
				*===update
				method="update"
			
		 -->
		<!-- 重點 -->
		<action name="quick2_*" class="cn.nanjin.action.QuickAction2" method="{1}">
			<result name="delete">/success.jsp</result>
			<result name="save">/save.jsp</result>
			<result name="update">/update.jsp</result>
		</action>
		<!-- 
			例如:
				http://localhost:8080/quick3_save_User.action
				第一個*===save
				第二個*===User
				method=saveUser
				
				http://localhost:8080/quick3_update_User.action
				第一個*===uodate
				第二個*===User
				method=updateUser
		 -->
		<action name="quick3_*_*" class="cn.nanjin.action.QuickAction3" method="{1}{2}">
			<result name="delete">/success.jsp</result>
			<result name="save">/save.jsp</result>
			<result name="update">/update.jsp</result>
		</action>
		
		<!-- 動態方法呼叫(瞭解)
				開啟動態方法呼叫(預設是關閉)
					xml配置簡單 如下配置
					頁面訪問url有要求
					
				配置一個常量:
					struts.enable.DynamicMethodInvocation = true
				
				例如:
					http://localhost:8080/Struts2_Day01/quick4!save.action
					http://localhost:8080/Struts2_Day01/quick4!update.action
		 -->
		<action name="quick4" class="cn.nanjin.action.QuickAction4">
			<result name="delete">/success.jsp</result>
			<result name="save">/save.jsp</result>
			<result name="update">/update.jsp</result>
		</action>
		
	</package>
	
	
	<!-- 載入其他的struts配置檔案,分模組開發 -->
	<!-- <include file="struts-customer.xml"></include>
	<include file="struts-linkman.xml"></include> -->
	
</struts>


struts.properties

只能配置常量 鍵值對
實際開發中 一般常量習慣在struts.xml中配置
沒什麼用

核心filter 初始化引數



Struts2的API

Action的定義的三種方式

1)Action可以定義成一個POJO

2)定義Action類實現Action介面
好處:規範開發 Action介面提供了5個直接使用的常量

3)定義的Action類繼承ActionSupport(重點)
子的功能更加強大 例如 可以進行國際化 表單校驗....



綜合案例:

需求

編寫程式實現查詢所有客戶資訊並回顯頁面

步驟


1.實體類 Customer.java

public class Customer implements Serializable {
	private Long cust_id;
	private String cust_name;
	private String cust_source;
	private String cust_industry;
	private String cust_level;
	private String cust_phone;
	private String cust_mobile;

2.hibernate對映Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.domain.Customer" table="cst_customer">
	<id name="cust_id">
			<generator class="native"></generator>
		</id>
		<property name="cust_name"></property>
		<property name="cust_source"></property>
		<property name="cust_industry"></property>
		<property name="cust_level"></property>
		<property name="cust_phone"></property>
		<property name="cust_mobile"></property>
</class>
</hibernate-mappin

3.hibernate主配置檔案 hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
	
<hibernate-configuration>
	<session-factory>
		<!-- 1、資料庫連線資訊 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///struts_demo</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">123456</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 2、hiebernate其他引數 可選 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		<!-- 3、載入對映 -->
		<mapping resource="com/test/domain/Customer.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

4.action 

public class CustomerAction extends ActionSupport {
     public String findCustomerList(){
    	try {
    		//業務處理
			CustomerService service =new CustomerServiceimpl();
			List<Customer> list =service.findCustomerList();
			ServletActionContext.getRequest().setAttribute("list", list);
			return "success";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
    	 
     }
}

5.serviceimpl

public List<Customer> findCustomerList() throws Exception {
		List<Customer> result =null;
		CustomerDao dao=new Customerimpl();
		result =dao.findCustomerList();
		return result;
		

	}

6.dao

	public List<Customer> findCustomerList() throws Exception {
		List<Customer> result =null;
		
		String hql ="from Customer ";
		Configuration conf =new Configuration().configure();
		SessionFactory factory = conf.buildSessionFactory();
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery(hql);
		result =query.list();
		
		tx.commit();
		
		session.close();
		factory.close();
		return result;
	}

7.struts.xml


<action name="customer_*" class="com.test.struts.CustomerAction" method="{1}">
		<result name="success">/jsp/customer/list.jsp</result>
		</action>

8.回顯頁面



相關文章