springMVC+Spring3+hibernate4整合實現增刪改查demo

需要的jar包:


項目結構:




配置文件的配置:

beans.xml(spring 的配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
						http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context-3.2.xsd
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"
>
  
<!-- 數據源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springmvc?useUnicode=true&characterEncoding=UTF-8"/><property name="user" value="root"/><property name="password" value="123"/><property name="initialPoolSize" value="5"></property><property name="minPoolSize" value="5"></property><property name="maxPoolSize" value="15"/><property name="checkoutTimeout" value="1000"/> </bean><!-- 配置sessionfactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false </value> </property> <property name="configLocations"> <list> <value> classpath*:config/hibernate.cfg.xml </value> </list> </property></bean> <!-- 配置事務管理器 --><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /></bean><tx:annotation-driven transaction-manager="transactionManager"/><!-- 自動掃描(自動注入) --><context:component-scan base-package="com.springmvc" /></beans> springmvc-servlet.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<!-- 自動掃描controller包下的所有類,使其認爲spring mvc的控制器 -->
	<context:component-scan base-package="com.springmvc.controller" />	

	<!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前後綴 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />


	

</beans>
hibernate配置文件的配置:(分離開來主要是爲了複雜項目管理更加方便)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 可以配置一個項目的多個映射類-->
<session-factory> <mapping class="com.springmvc.bean.User"/> </session-factory> </hibernate-configuration>
web.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:config/beans.xml</param-value>    
  </context-param>
  <!-- spring的監聽器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
<!-- 配置springmvc-->
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/Springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
<!-- 防止出現session異常-->
<filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
至此,所有的配置文件就配置好了,剩下的就是業務邏輯代碼了。

springmvc的controller:

usercontroller.java:

package com.springmvc.controller;

import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springmvc.bean.User;
import com.springmvc.dao.IUserDao;
/**springmvc的控制類
 * 
 * @author 董政
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Resource
	private IUserDao userservice;
	
	/**
	 * 更新用戶操作
	 * @param user 用戶對象
	 * @param req 
	 * @param rep
	 */
	@RequestMapping("/update")
	public void update(User user,HttpServletRequest req,HttpServletResponse rep){
		try {
			rep.setContentType("text/html;charset=UTF-8");
			//獲得輸出流
			OutputStream printWriter=null;		
			printWriter=rep.getOutputStream();		
			//對字符串進行轉碼操作
			User newuser=null;			
			//轉碼字符串 ,防止亂碼
			newuser=new User(Integer.parseInt(URLDecoder.decode(user.getUserId().toString(), "utf-8")), URLDecoder.decode(user.getUserName(), "utf-8"), URLDecoder.decode(user.getAge(), "utf-8"));	
					
			userservice.update(newuser);
			printWriter.write("su".getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 初始化界面
	 * @return
	 */
	@RequestMapping("/index")
	public String toIndex(HttpServletRequest req,HttpServletResponse rep){
		//查找集合
		List<User> users=userservice.getAllUsers();
		//放入作用域中
		req.setAttribute("userlist", users);
		
		return "Index";
	}
	
	/**
	 * 進入添加界面
	 * @return
	 */
	@RequestMapping("/toadd")
	public String toAdd(){
		return "add";
	}
	
	/**
	 * 初始化更新界面
	 * @param req
	 * @param id
	 * @return
	 */
	@RequestMapping("/toUpdate")
	public String toUpdate(HttpServletRequest req,Integer id){
		//查找要更新的數據
	   User user=userservice.getUsrById(id);
	   //放入作用域
		req.setAttribute("user", user);
		return "Userinfo";
	}
     /**
      * 刪除操作
      * @param req 請求
      * @param id 刪除的id
      * @param rep 響應
      * @return
      */
	@RequestMapping("/del")
	public String  del(HttpServletRequest req,Integer id,HttpServletResponse rep){
		    //刪除對應的數據庫數據
			userservice.delUser(id);
			//獲取數據集合
			List<User> users=userservice.getAllUsers();
			//放入作用域
			req.setAttribute("userlist", users);			
			return "Index";
			
	}
	/**
	 * 添加操作
	 * @param name 用戶名
	 * @param age 年齡
	 * @param rep 響應
	 */
	@RequestMapping("/add")
	public void add(String name,String age,HttpServletResponse rep){
		try {
			//設置ajax的返回類型
			rep.setContentType("text/html;charset=UTF-8");
			//獲得輸出流
			OutputStream printWriter=null;
					
			//ʵ實例化輸出流
			printWriter=rep.getOutputStream();			
			User user=null;		
			user = new User(null, URLDecoder.decode(name,"utf-8"), URLDecoder.decode(age,"utf-8"));
			
			userservice.addUser(user);
			//提示信息
			printWriter.write("su".getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
userdao接口:

package com.springmvc.dao;

import java.util.List;

import com.springmvc.bean.User;

public interface IUserDao {
    /**
     * 添加用戶操作
     * @param user 用戶
     */
	public void addUser(User user);
	/**
	 * 用戶集合
	 * @return  集合類型
	 */
	public List<User> getAllUsers();
	/**
	 * ͨ根據用戶iD查詢
	 * @param id
	 * @return user
	 */
	public User getUsrById(Integer UserId);
	/**
	 * ɾ刪除用戶
	 * @param userId
	 */
	public void delUser(Integer user);
	
	/**
	 * 更新用戶
	 * @param user
	 */
	public void update(User user);
}
實現類我就不貼出來了。
junit測試類:

package com.test;

import java.util.List;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.springmvc.bean.User;
import com.springmvc.dao.IUserDao;

public class TestUser {
	private static IUserDao userDao;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ApplicationContext cxt=new ClassPathXmlApplicationContext("/config/beans.xml");
		userDao=  (IUserDao) cxt.getBean("userService");
	}

	@Test
	public void test() {
		userDao.addUser(new User(null, "董政", "26"));
	}
    
	@Test
	public void update(){
		userDao.update(new User(1, "sss", "11"));
	}
	
	@Test
	public void getAll(){
		List<User> list=userDao.getAllUsers();
		System.out.println(list.size());
	}
	
	@Test
	public void getOne(){
		System.out.println(userDao.getUsrById(1).getAge());
	}
	@Test
	public void del(){
		userDao.delUser(3);
	}
}

截圖:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章