老九门洞房:struts2.1.6+spring整合

来源:百度文库 编辑:中财网 时间:2024/04/29 22:34:45
struts2整合spring 笔记(根据风中叶视频整理)
当然在看这个文章以前,你也可以参照struts2官网的配置说明http://struts.apache.org/2.x/docs/spring-plugin.html

01 登录页面login.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
   
   
   
   
   


02 登录成功页面result.jsp
    用户名是:

    密码是:

03 复制struts-2.1.6-all文件夹中的struts2-spring-plugin-2.1.6.jar和spring.jar到lib

04 在myeclipse添加spring开发支持,选择spring2.0,默认选择spring2 core libraryes,spring2 web libraries,最下面选择 复制JAR包到项目->finish
05 建包com.sdi.service,新建Interface
public interface IloginService {
public boolean isLogin(String userName,String userPwd);
}
06 建包com.sdi.service.impl,新建类LoginServiceImpl.java 实现接口
loginService

public class LoginServiceImpl implements IloginService {
public boolean isLogin(String userName, String userPwd) {
   if("admin".equals(userName) && "admin".equals(userPwd)){
    return true;
   }
   return false;
}
}

07 新建LoginAction.java类,并继承ActionSupport类

添加属性 private IloginService loginService; 并生成set,其中get不用生成,因为spring已经封装好了。
覆盖execute()方法:
public String execute() throws Exception {

   if(loginService.isLogin(userName, userPwd)){
    return SUCCESS;
   }else{
    return INPUT;
   }
}

08 修改struts.xml
-------------------------------修改前的---------------------------------------------

  
    /result.jsp
    /login.jsp
   
  


--------------------------------修改后的----红色加粗部分可以随便命名,但一定要和spring配置文件application.xml中的ID保持一致----------------------------------------

  
    /result.jsp
    /login.jsp
   
  



09 修改spring的配置applicatonContext.xml文件,该文件需要保存在Web应用的WEB-INF目录下。(其中id="loginAction"一定要和struts.xml中的命名一样)


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">



   scope="prototype"> //scope的值表示一次生成一个实例,线程更安全
   //loginService是LoginAction.java中的属性
    // loginService引用bean中的id的值
  




10 配置Spring监听器。在web.xml文件中增加如下内容:

  
    org.springframework.web.context.ContextLoaderListener
  



注:开发者实际上可以使用多个Spring配置文件,在web.xml中进行下列设置,从而使Spring的ApplicationContext通过匹配所给定模式的文件来初始化对象:


       contextConfigLocation
       /WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml

现在已经成功了,进行测试吧:)