九、action交给spring管理
1.在struts-config.xml中,配置代理请求
<!-- 不配置代理请求处理,收到login.do的请求后,web服务器查询web.xml把请求交给ActionServlet, ActionServlet查询struts-config.xml,填充表单并交给对应Action--> <!-- 配置代理请求处理,收到login.do的请求后,web服务器查询web.xml把请求交给ActionServlet, ActionServlet查询struts-config.xml,发现struts-config.xml中配置了代理请求处理,就去applicationContext.xml中寻找应该找哪个action--> <controller> <set-property value="processorClass" property="org.springframework.web.struts.DelegatingRequestProcessor"/> </controller>
2.loginAction中,将employeeService作为属性注入
2.1编辑loginAction,抽取出employeeService
package com.myz.web.actions; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import com.myz.domain.Employee; import com.myz.service.interfaces.EmployeeServiceInterface; import com.myz.web.forms.EmployeeForm; public class LoginAction extends DispatchAction { private EmployeeServiceInterface employeeService;
public EmployeeServiceInterface getEmployeeService() { return employeeService; } public void setEmployeeService(EmployeeServiceInterface employeeService) { this.employeeService = employeeService; } public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { EmployeeForm employeeForm=(EmployeeForm) form; Employee e=new Employee(); e.setId(employeeForm.getId()); e.setPassword(employeeForm.getPassword()); Employee loginUser=employeeService.loginCheck(e); if(loginUser!=null){ //登录成功则保存用户信息到session中 request.getSession().setAttribute("loginUser", loginUser); return mapping.findForward("ok"); }else{ return mapping.findForward("err"); } } }
2.2 applicationContext.xml中配置action
<!-- 配置action 而且配置scope可以解决action的单例的问题--> <bean name="/login" class="com.myz.web.actions.LoginAction" scope="prototype"> <property name="employeeService" ref="employeeService"></property> </bean>
2.3 action中type的配置信息可以移除
<action path="/login" parameter="flag" name="employeeForm"> <forward name="ok" path="/WEB-INF/mainFrame.jsp"></forward> <forward name="err" path="/WEB-INF/login.jsp"></forward> </action>
3.测试,输入正确用户id和密码能够登录,否则不能