Struts2与spring3的巧妙结合实现零配置

1、配置web.xml

 

<!-- springListener -->
	<context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- struts2Filter -->
	<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>*.action</url-pattern>
	</filter-mapping>

 

 

2、spring配置,使用全注解配置

 

<!-- 注解配置 -->
	<context:annotation-config></context:annotation-config>
	<context:component-scan base-package="com.example"></context:component-scan>

 

 

3、struts2的配置,这部分是关键

 

<constant name="struts.objectFactory" value="spring"></constant>
<!--允许使用*/*的配置-->
<constant name="struts.enable.SlashesInActionNames" value="true"></constant>
	
	<package name="restful" extends="struts-default">
		<action name="*/*" class="{1}Action" method="{2}">
			<result name="success">${forward_page}</result>
			<result name="redirect" type="redirect">${redirect_page}</result>
		</action>
	</package>

 

4、BaseAction,配合struts.xml用来控制页面跳转,传递属性

 

public class BaseAction
{
    public static final String SUCCESS = "success";

    public static final String REDIRECT = "redirect";

    private String forward_page;

    private String redirect_page;

    //转发
    public String forward(String viewPath)
    {
        forward_page = viewPath;
        return SUCCESS;
    }
    //重定向
    public String redirect(String viewPath)
    {
        redirect_page = viewPath;
        return REDIRECT;
    }
    //添加属性
    public BaseAction addAttr(String key, Object value)
    {
        Map<String, Object> request = (Map<String, Object>) ActionContext
                .getContext().get("request");
        request.put(key, value);
        return this;
    }

    public String getForward_page()
    {
        return forward_page;
    }

    public String getRedirect_page()
    {
        return redirect_page;
    }

}

 

 

5、自定义的Action

 

@Controller
public class AccountAction extends BaseAction
{
    public String add()
    {
        //转发
        return forward("/add.jsp");
    }

     public String get()
    {
        //重定向
        return redirect("get.jsp");
    }

    public String list()
    {
        @SuppressWarnings("unchecked")
        List list = new ArrayList();
        int count = 10;
        // 添加属性及跳转
        return addAttr("list", list).addAttr("count", count).forward(
                "/list.jsp");
    }

}

 

这样的好处就是可以省去一切struts2中Action的配置,当我们访问account/add.action时,自动调用AccountAction.add()方法。

如果我们想调用TestAction中的delete()方法,可以直接通过test/delete.action去调用。

在这里,我们采用的约定大于配置,如xxx/yyy.action,xxx对应Action的名字,此处对应xxxAction,yyy对应方法名.

 

 

你可能感兴趣的:(struts2,Spring3,整合,零配置)