Struts2的官方提供了完整的开发包,里面提供了示例项目的war包, 从war包中找需要的lib,及web.xml和struts.xml。仅从环境搭建来看的话,struts2还是很容易的。
官网打开太慢,百度搜索struts2下载,从pc6下载站下载
首先复制jar包,放到项目的lib中
在web.xml中,增加过滤器,来实现struts2
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
创建struts.xml,放在src根目录下即可
<?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.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index" />
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error"/>
</global-exception-mappings>
<action name="login" class="com.LoginAction">
<result type="chain"> <!-跳至下一个action-->
redirectAction
</result>
</action>
<action name="redirectAction" class="com.redirectAction">
<result >/success.jsp</result>
</action>
</package>
</struts>
LoginAction.java,和下面的action都放在com包下
package com;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class LoginAction extends ActionSupport implements ModelDriven{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String execute() throws Exception {
System.out.println("运行了action");
setName("lyj");
return "success";
}
public Object getModel() {
return null;
}
}
redirectAction.java
package com;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class redirectAction extends ActionSupport implements ModelDriven{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String execute() throws Exception {
System.out.println("进入了redirectAction");
System.out.println(name); //上个action设置了setName("lyj"); 这里就可以打印 lyj;说明chain方式可以把值带过来
return super.execute();
}
public Object getModel() {
return null;
}
}
index.jsp页面
<body>
<a href="login.action">连接</a>
</body>
其他页面就不写了