web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Struts2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 可以配置与spring集成的applicationContext配置文件,否则默认次文件应该在WEB-INF目录下 -->
<!-- <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> -->
<!-- struts2入口 -->
<filter>
<filter-name>struts2Filter</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- stuts2处理的映射url请求 -->
<filter-mapping>
<filter-name>struts2Filter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- 与spring集成配置的监听器 -->
<!-- <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> -->
</web-app>
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.1.7.dtd"
>
<struts>
<!-- 这句必须写上指定包,才会扫描,让注解起作用 -->
<constant name="struts.convention.action.packages" value="com.test" />
<package name="com.test" namespace="/test" extends="struts-default">
<!-- 指定全局的结果 -->
<global-results>
<result name="testGlobal" type="">/testGlobal.jsp</result>
</global-results>
<!-- 指定action -->
<action class="com.test.TestAction" name="test">
<!-- 指定action内起作用的结果 -->
<result name="test">/test.jsp</result>
</action>
<action class="com.test.TestAction" name="test2" method="f">
<result name="test">/test.jsp</result>
</action>
</package>
</struts>
action的java代码:
package com.test;
import com.opensymphony.xwork2.ActionSupport;
//未使用注解的action
public class TestAction extends ActionSupport{
//默认执行action执行execute方法
@Override
public String execute() throws Exception {
return "testGlobal";
}
public String f(){
return "test";
}
}
package com.test;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
//使用注解的action
@Namespace(value="/test2")//指定空间名
@ParentPackage(value="struts-default")//集成父package
@Results({//全局结果返回结果指定
//location指定返回的jsp页面
@Result(name="test",location="/test.jsp")
})
public class Test2Action {
//在方法上定义action的name
@Action("test2")
public String login(){
return "test";
}
}