spring mvc +hibernate注解版测试增,删,改,查 简单xml配置应用

14 篇文章 0 订阅

spring mvc +hibernate注解版测试增,删,改,查 简单xml配置应用

都说spring mvc好用,我学习了一段时间,真不觉得,都喜欢把spring mvc和struts2做比较,从开发效率上来说,觉没有struts 2快,就是有强大的注解功能,但对于大项目来说,用注解不好调试和维护吧!一说到xml配置,我插!一肚子火,太复杂了,太不好理解了,顶多和struts1不向上下,struts2的通配符用习惯了,再用这种方试感觉太慢了!也许我没发现更好的spring mvc配置吧!


评着好奇心总算把spring mvc+hibernate增删改查做了个简单应用!

项目原码免费下载:http://download.csdn.net/detail/liangrui1988/6797241


部分代码:

xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 

 <!-- 初始xml   classpath:/config/webConfig-action.xml classpath:config/webConfig-dao.xml-->
 <context-param>
	 <param-name>contextConfigLocation</param-name>
	 <param-value>classpath:config/config-dao.xml
	              classpath:config/config-sevice.xml
	              </param-value>
 </context-param>

   <!-- 监听 -->
 <listener>     
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 
 
 <!-- srping mvcConfig -->
 <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/config-springServlet.xml</param-value>
</init-param> 
<load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>springMvc</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 
 <!-- 乱码处理 -->
  <filter>  
   <filter-name>CharacterEncodingFilter</filter-name>  
     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
      <init-param>  
          <param-name>encoding</param-name>  
          <param-value>utf-8</param-value>  
      </init-param>  
       <init-param>  
          <param-name>forceEncoding</param-name>  
          <param-value>true</param-value>  
      </init-param> 
  </filter>  
  <filter-mapping>  
     <filter-name>CharacterEncodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
 </filter-mapping> 
 

 
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

</web-app>



config-springServlet.xml

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"	
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tool="http://www.springframework.org/schema/tool"
	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
	                    http://www.springframework.org/schema/aop 
	                    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
	                    http://www.springframework.org/schema/tool	                    
	                    http://www.springframework.org/schema/tool/spring-tool-3.2.xsd
	                 	http://www.springframework.org/schema/mvc
	                    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	                    
	
   <!-- 注解扫描 -->
	<context:component-scan base-package="org.rui"/>
	<context:component-scan base-package="org.controller"/>
		<context:component-scan base-package="org.bean"/>
	<!-- 开启注解 -->
	<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
	 -->
	 <mvc:annotation-driven/>
	<!-- 请求静态资源  如果请求方式配成/    而不是.do or .action 需如下配置-->
	<!-- <mvc:resources location="/image/" mapping="/image/**"/>
	<mvc:resources location="/jpg/" mapping="/jpg/**"/>
	<mvc:resources location="/css/" mapping="/css/**"/>
	<mvc:resources location="/js/" mapping="/js/**"/> -->
	
<!--页面视图层信息 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
	<property name="prefix" value="/"></property> <!--页面的前辍名 -->
	<property name="suffix" value=".jsp"></property> <!--页面的后辍名 -->
	</bean>
	
	<!-- 文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="utf-8" />
	<!-- 1024*1024*2=2097152 -->
	<property name="maxUploadSize" value="209715200" />
	<property name="maxInMemorySize" value="500000" />
	</bean>
	


	
	<!-- servlet映射列表 把有控制层的serlvet在这里 -->
	<!-- <bean id="serveltController" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	<property name="mappings">
	 <props>
	 <prop key="user.action">userController</prop>
	 </props>
	</property>
	</bean> -->
	

    
</beans>

config-dao.xml
<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"	
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tool="http://www.springframework.org/schema/tool"
	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
	                    http://www.springframework.org/schema/aop 
	                    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
	                    http://www.springframework.org/schema/tool	                    
	                    http://www.springframework.org/schema/tool/spring-tool-3.2.xsd"
	                    >

<!-- 数据库 -->
<!-- <bean id="authoritiesData" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/scurityOA"/>
<property name="username" value="root"/>
<property name="password" value="rui"/>
 </bean>  ?characterEncoding=utf-8-->
 
 <bean id="authoritiesData" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="rui"/>
 </bean>
 
   <!-- session  如果是注解一定要用Annotation xml则用localtion-->
   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
   <property name="dataSource" ref="authoritiesData"/>
   
<!--    <property name="mappingResources">
   <list>
   <value>/org/bean/Users.hbm.xml</value>
   </list>
   </property> -->
   
   <property name="hibernateProperties">
  <props>
  <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
  <prop key="hibernate.hbm2ddl.auto">update</prop>
  <prop key="hibernate.show_sql">true</prop>
  </props>
   </property>
   <!-- 注解方式配置hibernate bean -->
   <property name="configLocations">
   <list>
   <value>classpath:config/hibernate.cfg.xml</value>
   </list>
   </property>
   
   </bean>
   
   
   
<!--hibernateTemplate-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory"/>
</bean>

 <!-- 指定事务的sessionFacotry -->
<bean id="isTransaction" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>


<!-- 代理事务 -->
<!-- 
<bean id="proxyTransaction" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
   <property name="transactionManager" ref="isTransaction"></property>
	<property name="transactionAttributes">
		 <props>
		   <prop key="add*">propagation_REQUIRED</prop>
		    <prop key="save*">propagation_REQUIRED</prop>
		     <prop key="update*">propagation_REQUIRED</prop>
		      <prop key="delete*">propagation_REQUIRED</prop>
		      省略 知道有这种方法就好了,在dao层用sessionFactory 看视频讲的是这样做的,
		      我还是用我以前方式
		 </props>
	</property>
 </bean> -->

<tx:advice id="myAdvice" transaction-manager="isTransaction">
    <tx:attributes>
  <!--   这些开头的方法 设为只读事务 -->
      <tx:method name="get*" read-only="true"/>
       <tx:method name="find*" read-only="true"/>
       <tx:method name="login*" read-only="true"/>
       <tx:method name="query*" read-only="true"/>
      
   <!--    这些开头的方法 设为REQUIRED 如果存在一个事务 ,则支看当前事务。  如果没有则开启一个新事务                       
                        设为supports时  如果存在一个事务 ,则支看当前事务。如果没有则安非事务处理  delete -->
      <tx:method name="add*" propagation="REQUIRED"/>
      <tx:method name="save*" propagation="REQUIRED"/>
      <tx:method name="delete*" propagation="REQUIRED"/>
      <tx:method name="del*" propagation="REQUIRED"/>      
      <tx:method name="update*" propagation="REQUIRED"/>
      <tx:method name="do*" propagation="REQUIRED"/>
       <tx:method name="regsiter*" propagation="REQUIRED"/>
      <tx:method name="*" propagation="REQUIRED" read-only="true"/>
    </tx:attributes>
  </tx:advice>


<!--  配制事务方式二   定义那些方式使用这些规则   advisor 并将事务通知和规则组合在一起  *返回值  (..传的值) -->
<aop:config>
 <aop:pointcut id="DaoMethods" expression="execution(* org.service..*.*(..))"/>
 <aop:advisor advice-ref="myAdvice" pointcut-ref="DaoMethods"/>
</aop:config>

<bean name="userDao" class="org.dao.imp.UserDaoImp">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>

<!-- 注入数据库  -->
<!-- <bean id="dataIOC" class="com.oa.jdbc.OaJdbcDao" >
<property name="dataSource" ref="authoritiesData"/>
</bean> -->

</beans>



UserController.java

package org.controller;

import java.util.List;

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

import org.bean.User;
import org.service.Service;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;


@Controller
public class UserController {//userController

	@Resource(name="userService")
	private Service userService;
	
	
	@RequestMapping("/spirng/helloSpring")
	public String helloSpring(HttpServletRequest request){
		//spring 的上下文
		@SuppressWarnings("unused")
		WebApplicationContext ac1=WebApplicationContextUtils.
			getWebApplicationContext(request.getSession().getServletContext());
		//spring mvc的上下文
		WebApplicationContext ac2=RequestContextUtils.getWebApplicationContext(request);
		
		
		System.out.println(userService.helloSpring());
		return "/show";
	}
	
	//add user
	@RequestMapping("/userdemo/addUser")
	public String addUser(User user,HttpServletRequest request){
	
		System.out.println(user.getUsername()+user.getAge());
		try {
			userService.add(user);
		} catch (Exception e) {
			// TODO: handle exception
			 return "error";  
		}
		List<User> userList=userService.getAll();
		request.setAttribute("userList",userList);
		 return "userList";    
	}
	
//select user 
	@RequestMapping("/userdemo/userList")
	public String showUserList(HttpServletRequest request){
		
	List<User> userList=userService.getAll();
	System.out.println(userList.size());
	
	request.setAttribute("userList",userList);
       return "userList";    
	}
	
	//show edit uesr
	
	@RequestMapping("/userdemo/showEditUser")
	public String showEditUser(String uuid,HttpServletRequest request){
		
	User user=userService.getSingleUser(uuid);
	request.setAttribute("user",user);
	return "editUser";
	}
	
	//edit user
	@RequestMapping("/userdemo/editUser")
	public String editUser(User uesr,HttpServletRequest request){
		
	try {
	   userService.update(uesr);
		} catch (Exception e) {
			 return "error";    
	}
	
	List<User> userList=userService.getAll();
	request.setAttribute("userList",userList);
	return "userList";
	}
	
	//delete user
	@RequestMapping("/userdemo/deleteUser")
	public String deleteUser(String uuid,HttpServletRequest request){
		
		System.out.println("ddd");
	try {
	   userService.delete(userService.getSingleUser(uuid));
		} catch (Exception e) {
			 return "error";    
	}
	
	List<User> userList=userService.getAll();
	request.setAttribute("userList",userList);
	return "userList";
	}
	
}
userList.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'userList.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
  </head>
  
  <body>
  
  <h2 style="width: 980px;text-align: center;">用户列表</h2>
  <a href="${pageContext.request.contextPath}/annotationAdd.jsp">添加用户</a>
   <table width="980px">
   <tr>
   <td>t姓名</td>  <td>年龄</td>  <td>操作  </td>
   </tr>
   
   <c:forEach var="tempList" items="${userList}">
	   <tr>
	   <td>${tempList.username}</td>
	   <td>${tempList.age}</td>
	   <td> 
	   <a href="javascript:enditUser('${tempList.id}');">编辑</a>
	   <a href="javascript:deleteUser('${tempList.id}');">删除</a>
	      </td>
	   </tr>
   </c:forEach>
  
   </table>
   <script type="text/javascript">
   

   //编辑
   function enditUser(id){
   location.href="/springmvc2/userdemo/showEditUser.do?uuid="+id;
   }
   //删除
   function deleteUser(id){
   location.href="/springmvc2/userdemo/deleteUser.do?uuid="+id;
   }
   </script>
   
  </body>
</html>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值