Spring整合案例

使用Struts2、Spring和Hibernate进行开发的小案例
applicationContext.xml:
     在applicationContext.xml中对Hibernate还有c3p0的控制反转和依赖注入。




	
	
		
		
		
		
	
	
	
	
		
		
			
				update
				true
				true
				org.hibernate.dialect.MySQLDialect
			
		
		
			
				demo/entity/Student.hbm.xml
			
		
	
	
	
	
		
	
	
	
	
		
	
	
	
	
		
	
	
	
	
		
	
	

web.xml:
在web.xml文件对Struts2的整合,加入Spring的核心监听器和Struts2的核心过滤器。
web.xml:


  
  
  
  
  	struts2
  	org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  
  
  	struts2
  	/*
  
  
  
 
  	org.springframework.web.context.ContextLoaderListener
  
   
   
   	contextConfigLocation
   	classpath:applicationContext.xml
   
  	
  
    index.jsp
  


以上的步骤就可以使Spring对Struts2和Hibernate进行整合
下面的是三层架构的程序:
Student:
package demo.entity;


public class Student {


	private int id;
	private String name;
	private String age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	
	
}




Student.hbm.xml:







	
	
		
			
		
		
		
		
	





StudentService:
package demo.service;


import java.util.List;


import demo.dao.StudentDao;
import demo.entity.Student;


public class StudentService {


	private StudentDao studentDao;
	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}
	
	public List findAll(){
		return studentDao.findAll();
	}
}






StudentDao:
package demo.dao;


import java.util.List;


import org.springframework.orm.hibernate4.HibernateTemplate;


import demo.entity.Student;


public class StudentDao {
	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}




	public List findAll(){
		return hibernateTemplate.loadAll(Student.class);
	}
}






StudentAction:
	package demo.action;


import java.util.List;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


import demo.entity.Student;
import demo.service.StudentService;


public class StudentAction extends ActionSupport {


	private StudentService studentService;
	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}
	
	public String list(){
		List list = studentService.findAll();
		ActionContext.getContext().put("list", list);
		
		return "success";
	}
}



成功执行程序后的跳转页面:
list.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>




  
    显示用户
    
	
	
	    
	
	
	


  
  
  
    
    	姓名:,id:,年龄:

Spring整合案例_第1张图片

以后的小案例就是简单的使用ssh2的框架进行开发的,希望能帮助到大家

你可能感兴趣的:(spring,spring)