承上篇、最基本的 Struts 所需檔案及擺放位置如下:
- src\struts.xml
- src\com.test.conntroller.hello.java
- WebContent\WEB-INF\web.xml
- WebContent\hello.jsp
hello.java 內容
Struts 中預設執行 execute() ;內容需返回 “success”。
package com.test.controller;
public class hello {
public string execute() {
return "success";
}
}
hello.jsp 內容
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!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=UTF-8">
<title>Hello</title>
<body>
Hello World
</body>
</head>
</html>
struts.xml 內容
這一行的內容可以在引入的 struts2-core.jar 這個檔案裡的 struts-2.X.dtd 中找到、並且依著所引入不同版本的 dtd 內容而修正(不用背)。
<?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>
<!-- struts-default 是繼承至struts-default.xml -->
<package name="hello" extends="struts-default">
<action name="hello" class="com.test.controller.hello" method="execute">
<!-- 派送View的地方 -->
<result name="success">
/hello.jsp
</result>
</action>
</package>
</struts>
web.xml 內容
<!-- Struts2 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>