现在的位置: 首页 > 综合 > 正文

SSH框架整合之Struts2和Spring整合

2014年09月24日 ⁄ 综合 ⁄ 共 1615字 ⁄ 字号 评论关闭

      今天在整合SSH框架的过程中,发现Struts2和Spring的整合稍微复杂一些,想想还是记一下笔记为妙,免得以后就忘了。

       整合Struts2和Spring框架,可以去Struts2的spring-plugin.html这个参考文档。

       (1)、首先,需要在web.xml文件中配置一下东西:

     

 <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   <!-- Context Configuration locations for Spring XML files -->
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> -->
   	    <param-value>classpath:beans.xml</param-value>
    </context-param>

   监听器的作用是使应用程序默认让Spring注入来初始化对象,如果Spring不能创建,那么框架会自己创建。第二句context-param主要用来指明,该去哪找Spring的beans.xml文件。

      (2)在action中的使用

        只需要在Action类前加上注解,通过Spring的注入来初始化Action,scope用来说明采用多例模式,即每次请求都要新建一个action类。以往我们用Spring来通过注解注入一个bean的时候,要用@Component。但是因为Struts-Spring-plugins提供了一个容器用来装action的初始化对象,而dao和service层的对象是在Spring提供的容器中。而且,action的是通过name来自动装配的。当时我们也可以用加上@Component("名字")来制定action初始化的名字。

@Component("register")
@Scope("prototype")
// RegisterAction在struts.xml中的名字
public class RegisterAction extends ActionSupport implements ModelDriven<UserInfo> {

	private UserInfo userInfo=new UserInfo();
	
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	@Resource(name = "userService")
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String register() {
		User user = new User();
		user.setUsername(userInfo.getUsername());
		user.setPassword(userInfo.getPassword());
		boolean flag = userService.exists(user);
		if (!flag) {
			userService.add(user);
			return "success";
		}
		return "fail";
	}

	public UserInfo getModel() {
		// TODO Auto-generated method stub
		return userInfo;
	}
}


【上篇】
【下篇】

抱歉!评论已关闭.