首先必须要spring2.5以上版本,其次必须加入struts2中的struts2-spring-plugin.jar包,最后在struts.properties中加入一行如下:
struts.objectFactory=spring
然后配置struts.xml文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="struts" namespace="/" extends="struts-default">
<!-- 注意由spring接管action必须符合spring的命名规定,也就是TestAction的class标识为开头小写testAction。 -->
<action name="test" class="testAction" method="test">
<result name="success">/pages/test.jsp</result>
</action>
</package>
</struts>
由于用了基于注释的spring3,就不用再配置spring的xml文件里,直接来看一下这个TestAction类的spring注释 :
package com.myweb.web.action;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.myweb.modal.ibatis.Month;
import com.myweb.service.MonthService;
/**
* @author jsczxy2
* 使用@Controller进行spring托管 注意要加scope不然spring会以默认单例形式运行struts2
*/
@Controller
@scope("prototype")
public class TestAction extends BaseAction {
Logger log = Logger.getLogger(getClass());
private String msg;
private List<Month> months;
@Autowired
private MonthService monthService;
public String test(){
months = monthService.findIMonths();
for(Month m : months){
System.out.println(m.getName()+":"+m.getTotal());
}
return SUCCESS;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<Month> getMonths() {
return months;
}
public void setMonths(List<Month> months) {
this.months = months;
}
}
一切搞定,献上页面测试一下:
<!-- struts2不推荐使用JSTL,如果要使用el表达式,请注意加入isELIgnored="false" -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:forEach var="month" items="${months}">
${month.name}花费:${month.total}元 <br/>
</c:forEach>
</body>
</html>