4、分離商務邏輯l Action應該只負責畫面遷移的控制,而商務邏輯的具體細節應該封裝到業務層,Action只要調用業務介面就行了l 這裡將Action中的商務邏輯移到業務類中,並使用Spring的Bean機制進行管理(1)建立業務介面和業務類l 業務介面public interface UserService { public boolean isUserValid(String userid, String password);}l 業務類public class UserServiceImpl implements UserService { public boolean isUserValid(String userid, String password) { return "123456".equals(password); }}(2)追加Spring能力l 右擊Samples工程,MyEclipse -> Add Spring Capabilities:l 為了減少不需要的jar檔案發布到工程中,這裡指向BuildPath追加Spring2.0 Core Libraries,其他需要的jar檔案手工追加:Ø spring-aop.jarØ spring-dao.jarØ spring-remoting.jarØ spring-struts.jarØ spring-support.jarØ spring-web.jar(3) 修改struts-config.xmll 使用Spring的代理RequestProcessor替代Struts預設的RequestProcessor: <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />l 註冊Spring的Struts Plugin,指定Bean設定檔路徑: <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/classes/org/xqtu/samples/bean/samples-services.xml, /WEB-INF/classes/org/xqtu/samples/bean/samples-actions.xml" /> </plug-in>l Spring支援多Bean設定檔,這裡按功能層次在不同Bean檔案中定義(4) 定義Bean檔案l samples-services.xml <bean id="userService" class="org.xqtu.samples.service.impl.UserServiceImpl"> </bean>l samples-actions.xml <bean name="/login" class="org.xqtu.samples.web.action.LoginAction"> <property name="userService" ref="userService" /> </bean>l 注意,name屬性的值要和struts-config.xml中Action的path屬性相同(5) Action類注入業務介面 private UserService userService; public void setUserService(UserService userService) { this.userService = userService; }l 注意,這裡定義是UserService介面,而Bean檔案中定義的是實作類別UserServiceImpl(6) 修改Action類,調用業務方法 if (userService.isUserValid(loginForm.getUserid(), loginForm .getPassword())) { request.setAttribute("userid", loginForm.getUserid()); return mapping.findForward("success"); }(7) 顯示Spring的Log資訊l 為了在控制台顯示Spring的Log資訊,可以在src目錄下追加log4j.properties:log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p %c - %m%nlog4j.rootLogger=INFO, stdoutlog4j.logger.org.springframework=DEBUG