首先,导包。
然后在src中建一个struts.xml文件,文件的内容可以从struts-default.xml(在struts2-core包中)中复制
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>
</struts>
这时这个xml文件就变成这个可爱的蓝轮轮
再对web.xml文件进行配置
<!-- struts核心控制器:负责拦截所有的用户请求,(获取请求路径,然后根据路径到struts配置文件找到相关的action节点,得到节点中的class属性,根据反射机制实例化类,调用相关方法) -->
<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文件中的apps中的随意一个文件放到tomcat中运行,查看源码,源码里面有。
现在环境就搭建好啦啦啦~~~
now,我们来进行测试
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">
<package name="userModule" extends="default" namespace="/user">
<action name="save" class="com.nic.control.HelloWorld" method="save">
<!-- 返回页面,type:默认是dispatcher请求转发,重定向redirect -->
<result name="success" type="redirect">/index.jsp</result>
<result name="fail" type="redirect">/index.jsp</result>
</action>
</package>
<struts>
HelloWorld.java
public class HelloWorld {
public String save(){
System.out.println("这是保存方法");
return "success";
}
再写一个简单的index.jsp页面。
通过本地网址http://localhost:8080/struts1/user/save访问。运行后转到index.jsp页面,控制台输出:这是保存方法