Struts中使用Spring装配各个组件
好处:运行期才对组件进行注入,减少依赖。
Struts和Spring结合需要完成以下的2点。
1。在Struts的配置文件中添加Spring插件,
<plug-in className="org.springframework.web.struts.ContextLoaderPlugin">
<set-property property="contextConfigLocation" value="/WEB-
INF/applicationContext.xml">
</plug-in>
2.修改RequestProcessor
//和Spring集成后的自定义RequestProcessor
public class EncodingProcessor extends
DelegatingTilesRequestProcessor {
public void process(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
super.process(request, response);
}
RequestProcessor被用来在Struts进行请求的处理,EncodingProcessor属于自定义的RequestProcessor,这个类继承了Spring框架的
DelegatingTilesRequestProcessor,这样当处理用户请示需要用到Action时,就需要转移控制权,到Spring的配置文件中去寻找相应的Action来进行处理。
spring的组件配置文件3点:连数据库;注入(DB,DAO,Service,Action);事务
Spring在web.xml的配置
<!-- 下面是Spring应用配置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>context</servlet-name>
<servlet-
class>org.springframework.web.context.ContextLoaderServlet</servlet
-class>
<load-on-startup>1</load-on-startup>
</servlet>
eg.餐费管理系统(《Eclipse Web 开发从入门到精通》)
用于控制业务流程的Action类,用于实现业务逻辑的Service类,以及用户数据访问的DAO类。这些类在传统的做法中,通常在代码中通过互相调用组织在一起,在编译期就耦合在了一起,一旦某些代码发生了改变,就需要对耦合在一起的程序进行重新编译,这样维护起来就比较困难。
Spring框架的依赖注入解决了这个问题,Spring把应用中的各个组件通过配置文件组织在了一起,各个组件之间的依赖关系在运行期注入,这样,如果某些代码发生了改变就不需要对所有的代码全部重新编译,提高了维护的效率,同时也降低了组件之间的耦合程序。Struts能够和Spring进行很好的结合,结合后Struts中的Action就可以被Spring进行管理,从而也实现了在运行期对Action的依赖注入。
//和Spring集成后的自定义RequestProcessor
public class EncodingProcessor extends
DelegatingTilesRequestProcessor {
public void process(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
super.process(request, response);
}
}
//和Spring集成之前的自定义RequestProcessor
//public class EncodingProcessor extends TilesRequestProcessor {
//
//
// public void process(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
//
// request.setCharacterEncoding("UTF-8");
// response.setContentType("text/html;charset=UTF-8");
// super.process(request, response);
// }
//
该系统的MVC结构
视图:
jsp,actionForm
控制:
web.xml,sturts-config.xml,
Action:EmplyeeOperateAction,EmplyeeRegistAction,...
模型:
javaBean:Emplyee.java
业务逻辑:applicationContext.xml, IEmployeeService,
EmplyeeServiceImpl(使用DAO),..
数据访问:Hibernate.cfg.xml,Emplyee.hbm.xml.
EmployeeDao.*(访问数据库的各种操作)