Spring的作用
关于Spring在SSI框架中扮演的角色,大家可以参考SSH,然后去baidu。 此处就不便说明,因为个人还没有找到比较权威的书籍关于描述Spring的作用。
准备jar包
较第一个项目,本例需额外添加spring.jar和struts2-spring-plugin-2.1.6.jar
代码实现
1. 复制第一个项目,命名为StrutsSpring,并修改其Web Context-root为/StrutsSpring即可
操作步骤: 右击StrutsSpring --> Properties --> 在弹出的对话框中展开“MyEclipse” --> 选则Web。如图
2. 修改web.xml文件
在web.xml文件增加以下代码:
<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>
3. 修改EmpAction.java文件。 以下为全部代码
package controller; import java.util.List; import dao.EmpDAO; import entities.Emp; /** * <dl> * <dt><b>Description:</b></dt> * <dd> * deal with any action * </br> * </br><em>Copyright© 2011-2014 E.T.Crazy</em> * </dd> * </dl> * @version 2012-4-17 * @author E.T.Crazy */ public class EmpAction { // 封装处理结果的属性, 添加getter和setter方法 private Emp emp; private List<Emp> list; // 封装用户请求的属性, 添加getter和setter方法 private int id; // DAO组件, 一定要添加注入组件所必须的setter方法 private EmpDAO empDAO; // 处理用户请求的execute方法 public String execute(){ list = empDAO.findAll(); return "list"; } public Emp getEmp() { return emp; } public void setEmp(Emp emp) { this.emp = emp; } public int getId() { return id; } public void setId(int id) { this.id = id; } public List<Emp> getList() { return list; } public void setList(List<Emp> list) { this.list = list; } public void setEmpDAO(EmpDAO empDAO) { this.empDAO = empDAO; } }
4. 修改struts.xml文件, 以下为全部代码:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <package name="Emp" extends="struts-default"> <!-- 配置emp.action, class值为Spring的配置文件中处理该action的bean id --> <action name="emp" class="EmpActionRef"> <result name="list">/infos.jsp</result> </action> </package> </struts>
5.新建xml文件, 命名为applicationContext.xml。 以下为全部代码
<?xml version="1.0" encoding="UTF-8"?> <!-- DTD描述错误,是最容易使项目发生莫名其妙的问题。请注意。。。 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- 让Spring管理的Action实例 --> <bean id="EmpActionRef" class="controller.EmpAction" scope="prototype"> <!-- 依赖注入DAO组件 --> <property name="empDAO" ref="EmpDAO"></property> </bean> <!-- 定义DAO组件,其实现类是dao.EmpDAO --> <bean id="EmpDAO" class="dao.EmpDAO"></bean> </beans>
6. 其余的数据连接管理类、JavaBean、index.html均可不动
7. 启动Tomcat、发布项目。 访问http://localhost:8080/StrutsSpring/index.html。若出现以下界面,则项目成功
运行过程
运行过程,如图