struts2拦截器
struts2中关键的就是两个文件,一个是struts.xml(名字不可变),一个是web.xml.(项目自带)
代码例子
public class HelloAction {
public String hello(){
System.out.println("hello world");
return "success";
}
}
看一下struts.xml文件
<constant name="struts.devMode" value="true"></constant>
<!-- <constant name="struts.deMode" value="true"></constant> -->
<package name="hello" namespace="/hello" extends="struts-default">
<action name="HelloAction" class="cn.itmeima.a_hello.HelloAction" method="hello">
<result name="success" >/hello.jsp</result>
</action>
</package>
其中的name=“struts.demode” value="true"这个代表的是热加载的意思,开发模式下用,这样修改xml文件可以不用重新启动项目。
namespace="/hello"启动项目是地址栏的倒数第二个单词,当输入xxx./hello/HelloAction就会转发到hello.jsp页面。
HelloAction代表的就是上面的HelloAction这个类,然后匹配method方法,当返回success的时候和result中name对应上就可以转发到hello.jsp页面了。
一个xml中还可以引用其他的struts.xml。
<include file=" cn/itmeima/b_dynamic/struts.xml"></include>
dispatcher代表转发不会跳转页面
redirect代表重定向会跳转页面
默认type是dispatcher,如果换成redirect走方法就会跳转url。
<result name="success" >/hello.jsp</result>
web.xml中还需要配置
<display-name>struct2_day1-hh</display-name>
<!-- <context-param>
<param-name>struts.i18n.encoding</param-name>
<param-value>UTF-8</param-value>
</context-param> -->
<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>
其中的url-pattern中的/*代表的是拦截所有的页面。