天天看點

如何在IDEA中使用Struts2架構

學習筆記

實作目标:在index.html中點選按鈕跳轉到next.html

目錄

  • ​​使用maven建立web項目​​
  • ​​在pom.xml中添加struts架構的依賴​​
  • ​​建立action(java類)​​
  • ​​建立struts主配置檔案​​
  • ​​在web.xml中添加過濾器​​
  • ​​建立網頁檔案​​
  • ​​效果示範​​

使用maven建立web項目

可參考:​​項目管理工具 Maven 的下載下傳,安裝,配置以及項目的建立和管理​​

項目結構

如何在IDEA中使用Struts2架構

在pom.xml中添加struts架構的依賴

添加依賴

<dependencies>

<!--    struts2依賴-->
    <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>2.5.26</version>
    </dependency>

  </dependencies>
      

建立action(java類)

如何在IDEA中使用Struts2架構

代碼

package test;

import com.opensymphony.xwork2.ActionSupport;

public class Mytest extends ActionSupport {

    public String getinfo(){
        return SUCCESS;
    }

}
      

建立struts主配置檔案

在resource檔案夾中建立struts的主配置檔案struts.xml(名稱固定,位置固定)

如何在IDEA中使用Struts2架構
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <package name="demo" extends="struts-default" namespace="/">
<!--        index.html送出的路徑就是此處的name-->
<!--        class表示action(java類)的路徑-->
<!--        method表示action中的方法名-->
        <action name="login" class="test.Mytest" method="getinfo">
<!--            name表示action中的傳回值-->
<!--            标簽中的值表示要跳轉的網頁-->
            <result name="success">/next.html</result>
        </action>
    </package>
</struts>
      

在web.xml中添加過濾器

如何在IDEA中使用Struts2架構

添加過濾器

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


  <filter>
<!--    過濾器名稱-->
    <filter-name>action</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>action</filter-name>
<!--    過濾的請求,*表示所有請求-->
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>
      

建立網頁檔案

如何在IDEA中使用Struts2架構

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <center>
<!--        送出到對應的action中-->
        <form action="login">
            <input type="submit">
        </form>
    </center>
</body>
</html>
      

next.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <center>
        <h1>這是跳轉的網頁</h1>
    </center>
</body>
</html>
      

效果示範

如何在IDEA中使用Struts2架構