第一步:新建web项目把Struts2所用的jar包全部拷贝到lib下面
Struts jar下载地址:下载struts2jar包
第二步:配置拦截器(这一点一定要注意一定要记得配置,如果不配置会出现404的错误,这上面吃过不少亏的)
第三部:编写一个类继承ActionSupport重写execue的方法。
第四步:配置struts配置文件。
下面是具体的代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></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>
继承ActionSupport实现ModleDirver接口
package com.ygc.struts.main;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.ygc.struts.modle.Students;
@SuppressWarnings("serial")
public class StudentAction extends ActionSupport implements ModelDriven<Students>{
private Students studnets = new Students();
@Override
public String execute() throws Exception {
System.out.println(getModel().getId());
System.out.println(getModel().getAge());
return "success";
}
@Override
public Students getModel() {
return studnets;
}
private void add(){
}
}
ActionSupport所用的Students类
package com.ygc.struts.modle;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Students implements Serializable {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
struts配置文件
<?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>
<constant name="struts.i18n.encoding" value="GBK" />
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="com.ygc.struts.main.StudentAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
最后运行的地址:http://localhost:8080/root/hello.action?id=12&age=34 其中root为根目录、hello为配置的action。
最后附上源码:源码下载