Struts2學習筆記(二):第一個struts2應用開發

來源:互聯網
上載者:User

在預設的設定檔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>
<package name="jim" namespace="/test" extends="struts-default">
<action name="helloworld" class="com.jim.action.HelloWorldAction" method="execute" >
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>
</struts>

在struts2架構中使用包來管理Action,包的作用和java中的類包是非常類似的,它主要用於管理一組業務功能相關的action。在實際應用中,我們應該把一組業務功能相關的Action放在同一個包下。

 

配置包時必須指定name屬性,該name屬性值可以任意取名,但必須唯一,他不對應java的類包,如果其他包要繼承該包,必須通過該屬性進行引用。包的namespace屬性用於定義該包的命名空間,命名空間作為訪問該包下Action的路徑的一部分,如訪問上面例子的Action,訪問路徑為:/test/helloworld.action。 namespace屬性可以不配置,對本例而言,如果不指定該屬性,預設的命名空間為“”(Null 字元串)。

 

通常每個包都應該繼承struts-default包, 因為Struts2很多核心的功能都是攔截器來實現。如:從請求中把請求參數封裝到action、檔案上傳和資料驗證等等都是通過攔截器實現的。 struts-default定義了這些攔截器和Result類型。可以這麼說:當包繼承了struts-default才能使用struts2提供的核心功能。 struts-default包是在struts2-core-2.x.x.jar檔案中的struts-default.xml中定義。 struts-default.xml也是Struts2預設設定檔。 Struts2每次都會自動載入 struts-default.xml檔案。

 

包還可以通過abstract=“true”定義為抽象包,抽象包中不能包含action

HelloWorldAction.java:

 1 public class HelloWorldAction {
2 private String message;
3
4 public String getMessage() {
5 return message;
6 }
7
8 public String execute(){
9 message="我的第一個struts2程式";
10 return "success";
11 }
12 }

例子中使用到的/WEB-INF/page/hello.jsp如下:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP 'hello.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
${message}<br/>
</body>
</html>

可以使用EL運算式訪問Action中的屬性。

 

在struts1中,通過<action path=“/test/helloworld”>節點的path屬性指定訪問該action的URL路徑。在struts2中,情況就不是這樣了,訪問struts2中action的URL路徑由兩部份組成:包的命名空間+action的名稱,例如訪問本例子HelloWorldAction的URL路徑為:/test/helloworld (注意:完整路徑為:http://localhost:連接埠/內容路徑/test/helloworld)。另外我們也可以加上.action尾碼訪問此Action。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.