struts2使用總結

          struts2是我最先使用的java MVC框架,在天朝也是很火熱的,公司的項目也全部用struts2習慣了struts2的開發模式後,甚至感覺web後臺開發就是struts2模式,因爲估計本文會很長,所以會不間斷地更新。首先,是struts2的官方api,他是放在struts官網中下載頻道的fullleast那個包裏(反正就是最大的那個包),下以後打開有個doc文件夾,裏面還有個doc文件夾,打開裏面的index.html即可。如圖:

也可以直接在這裏下載:Struct2 API下載

1,struts2安裝

       我採用的是maven安裝方法,請先參考J2ee開發環境的建立,然後是查看最新的struts2的版本是哪個,這個不用去struts2的官網,可以直接在mavenSearch中查看,輸入struts2,下面顯示的最新可用版本是2.3.24.1,好,在項目中的pom.xml中加入如下代碼:

 <dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.24.1</version>
		</dependency>

保存,在eclipse中就會自動下載文件並添加到項目路徑,然後在項目中的web.xml中,加入如下代碼

<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>

即可安裝成功。

2,struts.xml配置

     在src/main/resources(爲什麼是這個目錄,請看maven教程)中新建struts.xml,代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

	<constant name="struts.devMode" value="true"></constant>
	<package name="felcx" extends="struts-default">
            <action name="register*" class="action.RegisterAction" method="{1}">
            <result name="success">/register.jsp</result>
            <result name="input">/register.jsp</result>
            </action>
	</package>
</struts> 
個人很喜歡上面這種配置,如果訪問的是registercreate,就會使用RegisterAction中的create方法,既沒有難看的!,可以實現一個action處理多個不同的請求,關於這個配置,有大神寫有文章:structs2.xml配置非常不錯的
3,運行程序

      運行程序,如果是在eclipse中運行程序,可參考J2ee開發環境的建立,打開服務器後,在瀏覽器中輸入localhost:8080/項目名/index.action,即可跳到index


二、Struts taglib

   Struts的tag是個好東西,運用好的話可以節省很多的開發時間。

首先是引用struts庫,這裏有個技巧,利用jsp的靜態引用方法,引用一個base.jsp文件,如

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!doctype html >
<html>
<head>

</head>
<body>

</body>
</html>

也可以加入js,css,等通用性的文件,這樣就一勞永逸。

在其他jsp頁面中,這樣引用:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@include file="Base.jsp" %>
<!doctype html >
即可使用通用性的功能。

1、<s:property>      輸出服務端的值,即服務器,網頁內容傳值。

首先,服務器中的值需要有set,get方法(不能使用mMesss)這樣一個小寫後面一個大寫的形式,因爲eclipse生成set,get方法後是setMmEsss,非常不好看,並且structs識別不出,請使用最少2個小寫開頭的變量。如:

public class HelloAction extends BaseAction {
	private MessageStore message;
	
	public String execute() throws Exception{
		message=new MessageStore("hello man");
		logger.error("hello");
		return SUCCESS;
	}

	public MessageStore getMessage() {
		return message;
	}

	public void setMessage(MessageStore message) {
		this.message = message;
	}

	
}

那麼在jsp中,可以這樣用:

<h1><s:property value="message.msg"/></h1>

前提條件是在strut.xml中設置,並且請求hello.action.

'

	<action name="hello" class="action.HelloAction">
			<result name="success">/hello.jsp</result>
		</action>

2、<s:url>    鏈接文件

   其實請求後臺的action有個問題,就是根目錄的路徑,如果不用<s:url>就需要在網址前加上<%=request.getContextPath()%>,很蛋疼,有這個標籤就簡單多了,

無參數:

<a href="<s:url action='hello'/>">hello world</a>
有參數:

<s:url action="hello" var="helloLink">
	<s:param name="userName">FelcxHuang</s:param>
</s:url>
<p><a href="${helloLink}">tiao zhuan</a></p>

3、<s:form>,<s:textfield>,<s:submit>     表單

    struct的這3個標籤的提供了一個簡單的,還過得去的表單,比如:

<s:form action="hello">
   <s:textfield name="userName" label="Your name"/>
   <s:submit value="Submit"/>
</s:form>


會解析出:

<table class="wwFormTable">
   <tbody><tr>
    <td class="tdLabel"><label for="hello_userName" class="label">Your name:</label></td>
    <td><input name="userName" value="" id="hello_userName" type="text"></td>
</tr>


   <tr>
    <td colspan="2"><div align="right"><input id="hello_0" value="Submit" type="submit">
</div></td>
</tr>


</tbody></table>

很明顯,代碼量減少很多,其結果也基本過得去。

還有其他的標籤,使用差不多,請參考api。

三、Struts session


session和request是常用的傳值工具,request struts已經封裝成上面討論的傳值方法了,而session,也封裝得很好實用,在BaseAction中加入以下代碼:

public class BaseAction extends ActionSupport implements SessionAware,ParameterNameAware{
	public static final Logger logger=LogManager.getLogger(BaseAction.class);
    public Map<String,Object> userSession;
	@Override
	public void setSession(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		userSession=arg0;
	}
	@Override
	public boolean acceptableParameterName(String parameterName) {
		
		boolean allowedParameterName=true;
		if(parameterName.contains("session")||parameterName.contains("request")){
			allowedParameterName=false;
		}
		return allowedParameterName;
	}

}

其必須實現
SessionAware
接口,另外一個接口是基於安全考慮,把請求參數名帶有的session或request的參數不理會,其他類只要繼承這個類,就可以通過
userSession

使用了,如下所示:

	private void incressHello(){
		Integer count=(Integer)userSession.get(HELLO_COUNT);
		if(null==count){
			count=1;
		}else{
			count++;
		}
		userSession.put(HELLO_COUNT, count);
	}


最後,關於struts生成的html美化,可以在<head>中用style重寫以下內容:

.wwFormTable {}
.label {font-style:italic; }
.errorLabel {font-style:italic; color:red; }
.errorMessage {font-weight:bold; color:red; }
.checkboxLabel {}
.checkboxErrorLabel {color:red; }
.required {color:red;}
.tdLabel {text-align:right; vertical-align:top; } 

最後的最後,sturts2外界裹貶不一,好的是其MVC思想非常徹底,也容易理解,不好的就是性能聽說不是很好。這個主要看項目的用途,聽說現在很多公司都用spring MVC,速度好像比struts快,但還是那句話,應該注意業務而非技術。


源代碼鏈接

示例代碼


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