1.新建一个web工程 //z-struts2-01
2.导入需要的jar包
3.配置web.xml文件
4.配置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>
<!--配置一个常量 :devMode:develop mode 开发模式 ,将value设为true:改了东西之后不需要重新启动,可以直接访问-->
<constant name="struts.devMode" value="true" />
<!-- 这里是访问路径 namespace/action name -->
<package name="default" namespace="/" extends="struts-default">
<action name="hello1">
<result>
/Hello.jsp
</result>
</action>
</package>
<!-- Add packages here -->
</struts>
流程:客户端(浏览器)访问服务器(tomcat),tomcat找到对应的工程(z-struts2-01),找到工程下的web.xml,web.xml中的filter去访问struts.xml文件,根据struts.xml中的命名空间和action、result访问资源(hello.jsp),返回给客户端。
我们还可以为struts.xml中的action添加class属性
<!-- package的作用和java中的一样,如果有多个action为 hello1,如果package的name不同,就不会冲突 -->
<!-- namespace以/开头,可以为空namespace=""即如果找不到对应的package下的hello1,就会访问这个hello1,一般情况下namespace和package的name相同 -->
<package name="default" namespace="/hello" extends="struts-default">
<action name="hello1" class="com.struts.hello.Hello" method="hello">
<!-- 这里指定了method,我们也可以不知道method,我们想调用class类中的某个方法,可以用http://localhost:8080/z-struts2-02/hello/hello1!execute这种方法来调用,在后面加上!方法名即可-->
<!-- 默认执行class对应的类中的execute方法,如果指定method,则访问method指定的方法 -->
<result name="success">/Hello.jsp</result>
<result name="hello">/index.jsp</result><!-- 当执行class对应的类中的hello方法时,跳转到 index.jsp-->
</action>
</package>
Hello.java
//继承ActionSupport类,重写execute方法,
public class Hello extends ActionSupport {
@Override
public String execute(){
return SUCCESS;//返回值对应的是Struts.xml中的result的name="success"的值
}
public String hello(){
return "hello";//返回值对应的是Struts.xml中的result的name="success"的值
}
}
使用通配符配置
1.web.xml文件不变
2.struts.xml如下
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<!-- 使用通配符配置action,hello*代表配对任何hello开头的,如:helloadd,{1}代表add,即去访问com.struts.hello.Hello的add方法-->
<action name="hello*" class="com.struts.hello.Hello" method="{1}">
<result>/hello{1}.jsp</result><!-- /hello{1}.jsp代表访问/helloadd.jsp -->
</action>
<!--匹Hello_add这样格式的-->
<action name="*_*" class="com.struts.hello.{1}" method="{2}">
<result>/{1}_{2}.jsp</result>
</action>
<!--这两种action同时使用时要注意:要确保第二个action的第一个*不要和第一个action的第一个单词一样,如果是hello_add,则会调用第一个action,那么第一个action的{1}就会变成_add,而Hello.java中找不到_add的方法,因此会报错-->
</package>
</struts>