(學習筆記)Struts2.3.3 入門與配置(一)
阿新 • • 發佈:2019-02-06
第二步:新建一個WEB專案,匯入以下9個jar架包
第三步:修改web.xml檔案,配置struts2過濾器
<?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" 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"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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>
第四步:新建一個index.jsp頁面,一個簡單額表單提交頁面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>struts2</title> </head> <body> <form action="Login.action" method="post"> username:<input type="text" name="username" /><br> password:<input type="password" name="password"/><br> <input type="submit" value="submit"> </form> </body> </html>
第五步:在src目錄新建一個包com.action,然後在包中新建一個類LoginAction
package com.action; /** * index.jsp form表單處理 * **/ public class LoginAction { private String username;//必須和表單中的name屬性一致 private String password; 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; } //這個方法必須要,處理返回最終結果,和配置檔案result name="success" 對應 public String execute() { return "success"; } }
第六步:在src目錄中新建一個struts.xml檔案,配置請求,action name="Login" 為 index.jsp 中 action的訪問地址,後面跟.action
<?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>
<!-- name隨便填 必須繼承struts-default namespace名稱空間,說白了就是資料夾 -->
<package name="struts2" extends="struts-default" namespace="/">
<!-- action 一次請求, name為請求路徑,這裡是指index.jsp中form action的路徑 -->
<!-- class 為處理請求的具體實現類 -->
<action name="Login" class="com.action.LoginAction">
<!-- result 根據處理結果,轉跳到相關頁面 -->
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
第七步:新建一個result.jsp檔案,顯示提交的內容
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>result</title>
</head>
<body>
${requestScope.username}<br>
${requestScope.password}
</body>
</html>
最終結果如下:
最後,部署到tomcat 執行