Struts 2 - URL 標籤



url 標籤負責生成 URL 字串。其優點是可以向標籤提供引數。讓我們透過一個示例來演示 url 標籤的使用。

建立 Action 類

package com.tutorialspoint.struts2;

public class HelloWorldAction {
   private String name;

   public String execute() throws Exception {
      return "success";
   }
   
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

建立檢視

讓我們使用以下內容建立HelloWorld.jsp

<%@ page contentType = "text/html; charset = UTF-8"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>

<html>
   <head>
      <title>Hello World</title>
   </head>
   
   <body>
      <s:url id = "login" action = "login" var = "myurl">
         <s:param name = "user">Zara</s:param>
      </s:url>

      <a href = '<s:property value = "#myurl"/>'>
      <s:property value = "#myurl"/></a>
   </body>
</html>

這裡我們正在生成一個指向“login.action”的 url 連結。我們將此 url 命名為“myurl”。這樣我們就可以在 jsp 檔案中的多個位置重複使用此 url 連結。然後,我們為 url 提供一個名為“USER”的引數。引數值實際上附加到查詢字串中,正如您從上面的輸出中看到的那樣。

當您想要根據 bean 的屬性值建立動態超連結時,URL 標籤非常有用。

配置檔案

您的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" />
   <package name = "helloaction" extends = "struts-default">
      <action name = "hello" 
         class = "com.tutorialspoint.struts2.HelloWorldAction" 
         method = "execute">
         <result name = "success">/HelloWorld.jsp</result>
      </action>
   </package>
</struts>

您的web.xml應該如下所示:

<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns = "http://java.sun.com/xml/ns/javaee" 
   xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id = "WebApp_ID" version = "3.0">
   
   <display-name>Struts 2</display-name>
   
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

右鍵單擊專案名稱,然後單擊匯出 > WAR 檔案以建立 WAR 檔案。然後將此 WAR 部署到 Tomcat 的 webapps 目錄中。最後,啟動 Tomcat 伺服器並嘗試訪問 URL https://:8080/HelloWorldStruts2/hello.action。這將生成以下螢幕:

Struts url tag
struts_data_tags.htm
廣告
© . All rights reserved.