在搭建Struts前, 請確保系統中的Servlet 等都正常
下載Struts-2.5.22-all.zip
並解壓 struts-2.5.22
將如下jar包放至 apache-tomcat-9.0.31/lib/
中,
並在工程中引用:
注意, 需將servlet-api.jar
引入
工程中結構如下:
源碼:
HelloWorldAction.java
package com.xx;
public class HelloWorldAction{
private String name;
public String execute() throws Exception {
if(name.isEmpty())
return "error";
else
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
struts.xml
(forHelloName 可以自定義名字)
<?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="forHelloName" namespace="/" extends="struts-default">
<action name="helloAct" class="com.xx.HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
<result name="index">/HelloWorld.jsp</result>
<result name="error">/Error.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://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>StrutsTestProj</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Error</h1>
</body>
</html>
HelloWorld.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World, <%=request.getParameter("name")%></h1>
<h1>Welcome, ${name} </h1>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome</h1>
<h1>truts2</h1><br><br>
<form action="helloAct" method = "POST">
<label for="name">Please enter your name</label><br /> <input
type="text" name="name" /> <br>
<input type="submit" value="Say Hello" />
</form>
</body>
</html>
Struts2 的基本執行流程