【SSH】Struts2

struts2簡單介紹

    struts2是一個相當強大的Java Web開源框架,是一個基於POJO的Action的MVC Web框架。它繼承了struts1和webwork2的優點,同時做了相當的改進。

    首先,去Struts官網(http://struts.apache.org),下載需要的版本,小編下載的是struts-2.3.28.1-all.zip。

    解壓struts-2.3.28.1-all.zip之後,我們來看一下里面的內容:

     創建一個Web Project項目,並導入一些基本jar包:


commons-fileupload:處理文件上傳組件

commons-io:fileupload上傳使用

commons-logging:ASF出品的日誌包

ognl:Object-Graph Navigation Language,對象圖導航語言,struts2框架通過其讀寫對象的屬性

struts2-core:struts2核心ja類庫

xwork-core:XWork類庫,struts2在其上構建

freemarker:struts2的UI標籤的模板使用Freemarker編寫

Struts2實例:

   web.xml:配置過濾器StrutsPrepareAndExecuteFilter

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>		<!--設置過濾  -->
  </filter-mapping>
</web-app>
</span></span>

   Action類繼承ActionSupport,寫界面實體和返回參數。默認執行execute()方法,返回相應的字符串,Struts.xml根據返回的字符串跳轉至相應頁面。

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;">public class LoginAction extends ActionSupport
{
	private String username;
	
	private String password;
	
	private int age;
	
	private Date date;
	
	public int getAge()
	{
		return age;
	}
	
	public Date getDate()
	{
		return date;
	}
	
	public void setDate(
			Date date)
	{
		this.date = date;
	}
	
	public void setAge(
			int age)
	{
		this.age = age;
	}
	
	public String getUsername()
	{
		return username;
	}
	
	public void setUsername(
			String username)
	{
		this.username = username;
	}
	
	public String getPassword()
	{
		return password;
	}
	
	public void setPassword(
			String password)
	{
		this.password = password;
	}
	
	
	public String execute(){
		return SUCCESS;
	}
}
</span></span>

   Struts.xml:放在src下,配置action對應的轉向頁面。將其放在src下,部署的時候,會自動發佈到WEB-INF/classes目錄下,也可以直接創建在WEB-INF/classes目錄下。

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><?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可以包含多個action,一個Struts可以包含多個package  -->
	<!--package起到分類的作用,支持繼承  -->
	<package name="struts2" extends="struts-default">
		<action name="login" class="com.jmj.struts2.LoginAction">
			<result name="success">/login_success.jsp</result>
			<result name="input">/login.jsp</result>
		</action>
	</package>
</struts>
</span></span>

   Struts.xml繼承了struts2的struts-default.xml中的內容。

JSP

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><!--action名稱和struts.xml中的action的name一樣  -->
	<form action="login">
		用戶名:<input type="text" name="username"><br>
		密碼:<input type="password" name="password"><br>
		年齡:<input type="text" name="age"><br>
		日期:<input type="text" name="date"><br>
		<input type="submit" value="登陸"> 
	</form></span></span>

顯示頁面

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
	<!--使用ognl獲取信息  -->
	用戶名:<s:property value="username"/><br>
	密碼:<s:property value="password"/><br>
	年齡:<s:property value="age"/><br>
	日期:<s:property value="date"/><br>
</body>
</html></span></span></span>

Struts2的優點:

1、良好的架構和設計

2、可重用、模塊化、擴展性好

3、Open source

自定義攔截器

   自定義攔截器必須實現interceptor接口,並覆蓋init()、destroy()、intercept()方法。AbstractInterceptor實現了interceptor接口,也可以直接讓攔截器類繼承此抽象類。繼承此類後,可以不用覆蓋init()、destroy()方法,只需要覆蓋intercept()方法即可。

   自定義攔截器類完成後,需要在struts.xml中配置:

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><packagename="struts2" extends="struts-default">

       <interceptors>

               <interceptorname="theInterceptor1" class="com.jmj.interceptor.TheInterceptor1">           <!—自定義攔截器的名稱和全路徑-->

                      <paramname="test">shengsiyuan</param>   <!—攔截器傳遞的參數,如果沒有參數,可以不寫這段代碼  -->

               </interceptor>

     </interceptors>

<!--在action中引用攔截器-->

       <action name=”login” class=”com.jmj.struts.LoginAction”>

              <interceptor-ref name=” theInterceptor1”/>

       </action>

</package></span></span>

   如果struts.xml中配置了自定義攔截器,則默認的攔截器將會失效,若還想使用默認攔截器,則可以加上<interceptor-ref name=”defaultStack”/>,且必須要將自定義攔截器放在默認攔截器前面。

   Struts.xml中還可以配置攔截器棧,攔截器棧可以引用多個攔截器,也可以引用其他攔截器棧。

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><interceptor-stack name=”myInterceptorStack”>

       <interceptor-refname=” theInterceptor1”/>

      <interceptor-ref name=”defaultStack”/>

</ interceptor-stack></span></span>

   Action中引用攔截器棧和引用攔截器是一樣的。

   還有一種攔截器---方法攔截器,需要繼承MethodFilterInterceptor抽象類,此攔截器根據方法名進行攔截,需要覆蓋doIntercept(ActionInvocation invocation)方法。

   Struts.xml中配置需要攔截的方法和不攔截的方法:

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><interceptor-refname=”theInterceptor3”>

       <param name=”includeMethods”>execute</param>

       <param name=”excludeMethods”>myExecute</param>

</interceptor-ref></span></span>

    注:在方法過濾攔截器中,如果既沒有指定includeMethods參數,也沒有指定excludeMethods參數,則所有的方法都會被攔截;如果僅僅指定了includeMethods參數,則只會攔截includeMethods中的方法,沒有包含在includeMethods中的方法就不會被攔截。

註解(Annotation)

   Struts2若想使用註解,需要引入struts2-convention-plugin-2.2.1.1.jar。

   註解配置在相應的Action類中:

@ParentPackage("struts-default")       //指定父包

@Action(value="login",results={@Result(name="success",location="/result.jsp"),@Result(name="input",location="/error.jsp")}) //配置action,如果想要指定多個result,需要使用“{}“括起來,result之間用逗號分隔。

@InterceptorRef("defaultStack")   //使用攔截器

@ InterceptorRefs({@InterceptorRef("theInterceptor1"), @InterceptorRef("defaultStack")})           //多個攔截器使用”{}”括起來,攔截器之前用逗號分隔

@ExceptionMappings({@ExceptionMapping(),@ExceptionMapping()})     //指定異常,多個異常處理使用“{}”括起來,異常處理之間用逗號分隔

注:若註解和配置文件衝突,則以註解爲準。

異常處理

   異常類需要繼承Exception抽象類。

   Struts.xml中配置異常類:

<global-exception-mapping>          //全局異常

<exception-mapping result=”名稱(自定義)” exception=”異常類全路徑”>           //局部異常

   注:局部異常優於全局異常。

   另外,action中的result也可以定義成全局的,使用<global-result>即可。

數據校驗器

   Struts2提供了大量的數據校驗器,包括字段優先校驗器和校驗器優先校驗器。

字段優先校驗器

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><validators>

       <field name=”username”>

              <field-validator type=”requiredstring”>         <!--必填項-->

                  <message>用戶名不能爲空!</message>

             </field-validator>

            <field-validator type=”stringlength”>     <!—字符串長度-->

                 <paramname=”minLength”>4</param>

                 <paramname=”maxLength”>6</param>

                 <message>用戶名長度介於${minLength}和${maxLength}之間</message>

          </field-validator>

     </field>

     <field name=”age”>

         <field-validator type=”required”>           <!--必填項-->

            <message>年齡不能爲空!</message>

        </field-validator>

       <field-validator type=”int”>      <!—數值型-->

            <paramname=”min”>10</param>

            <paramname=”max”>40</param>

            <message>年齡介於${min}和${max}之間</message>

       </field-validator>

    </field>

</validators></span></span>

   Requiredstring和required的區別就是requiredstring可以有空格字符串。另外,還可以校驗日期(設置type=”date”)、郵件(設置type=”email”)、網址(設置type=”url”)等等。

校驗器優先校驗器

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><validators>

     <validator type=”requiredstring”>          <!--必填項-->

          <paramname=”fieldName”>username</param>

          <message>用戶名不能爲空!</message>

     </validator>

     <validator type=”stringlength”>     <!—字符串長度-->

          <paramname=”fieldName”>username</param>

          <paramname=”minLength”>4</param>

         <paramname=”maxLength”>6</param>

         <message>用戶名長度介於${minLength}和${maxLength}之間</message>

     </validator>

</validators></span></span>
  以上是struts2的簡單使用,Struts2的深入學習有待繼續。


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