在netbean里创建一个库文件包含Struts2所必需的jar包
在web.xml插入语句
<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>
在源包下创建struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<!--name设置id 后面对应的类为action类-->
<action name="hello" class="action.HelloAction">
<result name="hello">/hello.jsp</result>
</action>
</package>
</struts>
创建一个hello类
package action;
public class HelloAction {
public String execute(){
return "hello";//对应 <result name="hello">/hello.jsp</result> 就会跳到hello.jsp
}
}
创建jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello struts2!</h1>
</body>
</html>
运行测试
实现简单的网页求和例子
写一个表单(此处没有用到任何struts的东西)
input.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>两数求和</title>
</head>
<body>
<form action="add" method="post">
请输入两个数:<br><br>
加数<input name="x"/><br><br>
被加数<input name="y"/><br><br>
<input type="submit" value="提交">
</form>
</body>
</html>
定义正数和负数显示的jsp网页
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
和为负数:<s:property value="sum"/>
</body>
</html>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
和为正数:<s:property value="sum"/>
</body>
</html>
注意用到了struts定义的标签,需要先加入该语句导入
<%@taglib prefix="s" uri="/struts-tags" %>
s:property value 访问Action值栈中的普通属性
编写action(最为关键的步骤)
package action;
public class SumAction {
private int x;
private int y;
private int sum;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getSum() {
return sum;
}
public String execute(){
sum=x+y;
if(sum>=0) return "+";
else return "-";
}
}
和spring一样写完类就在struts.xml配置文件加入该类的信息
注意这里action name必须和表单的一致
<action name="add" class="action.SumAction">
<result name="+">/Negative.jsp</result>
<result name="-">/Positive.jsp</result>
</action>
原文:https://www.cnblogs.com/OfflineBoy/p/14860443.html