简单的 Struts2 应用示例
以下是一个简单的Structs应用示例,以一个典型的表单提交应用作为示例:
1)创建index页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
<form action="hello" method="post">
<label>Enter your name</label><input type="text" name="name"/><br/>
<label>Enter your age</label><input type="text" name="age" /><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
2)创建Action类
Action类是Struts逻辑处理的核心,位于Controller层;
HelloAction.java
package action;
import org.apache.struts2.ServletActionContext;
public class HelloAction {
private String name;
private String age;
public String execute()throws Exception{
int age = Integer.parseInt(ServletActionContext.getRequest().getParameter("age"));
if(age>=18)
return "success";
else
return "fail";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
2)创建响应视图success.jsp,fail.jsp
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success</title>
</head>
<body>
Welcome, <s:property value="name" />
</body>
</html>
fail.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Fail</title>
</head>
<body>
Sorry,you are just <s:property value="age" />,under 18;
</body>
</html>
3)编辑 struts.xml 和 web.xml
struts.xml 应该放置classes目录下,但如果是在IDEA自动创建的struts工程,可以直接放置在src目录下,在编译打包时,IDEA会自动拷贝一个struts.xml的副本到classes下;
struts.xml
<?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>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<action name="hello" class="action.HelloAction" method="execute">
<result name="success">/success.jsp</result>
<result name="fail">/fail.jsp</result>
</action>
</package>
</struts
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<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>