阿O、不拽

导航

SSH框架整合入门helloworld两种事务管理方式(失败的自己)

这里的hibernate功能没有真正的使用

 

首先当然是jar包了:

 

struts2里面的Jar包:下载的struts2压缩包里面的struts-2.3.15.1\apps\struts2-blank,直接引入,另外就是struts2-spring-plugin-2.3.15.1.jar这个struts2和spring整合的jar

 

hibernate:  hibernate3.jar是肯定的,另外就是hibernate-distribution-3.6.10.Final\lib\required下面的必须的包,以及jpa下面的hibernate-jpa-2.0-api-1.0.1.Final.jar

 

spring:  spring.jar

   

cglib-nodep-2.1_3.jar

 

slf4j-api-1.5.0.jar

 

slf4j-log4j12-1.5.0.jar

 

还有就是连接数据库的(mysql为例:)mysql-connector-java-5.0.8-bin.jar

 

所有的包在图片里面有汇总

 

 

好了,下面开始进入正题:

 

web.xml:

 

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  5.   
  6.     <display-name>Struts Blank</display-name>  
  7.     <!-- 指定spring配置文件applicationContext.xml(可以多个)的位置 -->  
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>classpath*:applicationContext.xml</param-value>  
  11.     </context-param>  
  12.     <!-- 服务器启动的时候加载spring -->  
  13.     <listener>  
  14.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  15.     </listener>  
  16.     <!-- 配置struts2的filter -->  
  17.     <filter>  
  18.         <filter-name>struts2</filter-name>  
  19.         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  20.     </filter>  
  21.     <filter-mapping>  
  22.         <filter-name>struts2</filter-name>  
  23.         <url-pattern>*.action</url-pattern>  
  24.     </filter-mapping>  
  25.     <!-- 配置字符编码过滤器 -->  
  26.     <filter>  
  27.         <filter-name>encodingFilter</filter-name>  
  28.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  29.         <init-param>  
  30.             <param-name>encoding</param-name>  
  31.             <param-value>utf-8</param-value>  
  32.         </init-param>  
  33.     </filter>  
  34.     <filter-mapping>  
  35.         <filter-name>encodingFilter</filter-name>  
  36.         <url-pattern>/*</url-pattern>  
  37.     </filter-mapping>  
  38.     <welcome-file-list>  
  39.         <welcome-file>index.jsp</welcome-file>  
  40.     </welcome-file-list>  
  41.   
  42. </web-app>  

 

 

 

applicationContext.xml:注解事务管理,需要在方法上加@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)

 

Xml代码  收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:tx="http://www.springframework.org/schema/tx"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  5.                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  6.                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  7.     <!-- 启动注入功能 -->  
  8.     <context:annotation-config />  
  9.     <!-- 启动扫描component功能 -->  
  10.     <context:component-scan base-package="com.tch.test" />  
  11.     <span style="color: #000000;"><!-- 启动注解实物配置功能 -->  
  12.     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/></span>  
  13.     <!-- 数据源 -->  
  14.     <bean id="dataSource"  
  15.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  16.         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
  17.         <property name="url" value="jdbc:mysql://localhost:3306/test"></property>  
  18.         <property name="username" value="root"></property>  
  19.         <property name="password" value="root"></property>  
  20.     </bean>  
  21.     <!-- 事务管理器 -->  
  22.     <bean id="transactionManager"  
  23.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  24.         <property name="sessionFactory" ref="sessionFactory" />  
  25.     </bean>  
  26.     <!--读取数据库配置文件  -->  
  27.     <bean id="sessionFactory"  
  28.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  29.         <property name="dataSource" ref="dataSource"/>  
  30.         <property name="mappingLocations">  
  31.              <value>classpath:com/tch/test/ssh/entity/*.hbm.xml</value>  
  32.         </property>  
  33.         <property name="hibernateProperties">  
  34.             <props>  
  35.                 <prop key="hibernate.show_sql">true</prop>  
  36.             </props>  
  37.         </property>  
  38.     </bean>  
  39. </beans>  

 

xml文件配置的事务管理方式:这种方式不需要在方法上加@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)

 

Xml代码  收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:aop="http://www.springframework.org/schema/aop"  
  4.     xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  6.                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  7.                 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  8.                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  9.     <!-- 启动注入功能 -->  
  10.     <context:annotation-config />  
  11.     <!-- 启动扫描component功能 -->  
  12.     <context:component-scan base-package="test,com.tch.test" />  
  13.     <span style="color: #000000;"><!-- 不启动注解实物配置功能   
  14.     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>  
  15.     -->  
  16.     <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  17.         <tx:attributes>  
  18.             <tx:method name="get*" read-only="true"/>  
  19.             <tx:method name="select*" read-only="true"/>  
  20.             <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>  
  21.         </tx:attributes>  
  22.     </tx:advice>  
  23.     <aop:config>  
  24.         <aop:pointcut expression="execution(* com.tch.test.ssh..*.*(..))" id="testpointcut"/>  
  25.         <aop:advisor advice-ref="txAdvice" pointcut-ref="testpointcut"/>  
  26.     </aop:config></span>  
  27.     <!-- 数据源 -->  
  28.     <bean id="dataSource"  
  29.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  30.         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
  31.         <property name="url" value="jdbc:mysql://localhost:3306/test"></property>  
  32.         <property name="username" value="root"></property>  
  33.         <property name="password" value="root"></property>  
  34.     </bean>  
  35.     <!-- 事务管理器 -->  
  36.     <bean id="transactionManager"  
  37.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  38.         <property name="sessionFactory" ref="sessionFactory" />  
  39.     </bean>  
  40.     <!--读取数据库配置文件  -->  
  41.     <bean id="sessionFactory"  
  42.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  43.         <property name="dataSource" ref="dataSource"/>  
  44.         <property name="mappingLocations">  
  45.              <value>classpath:com/tch/test/ssh/entity/*.hbm.xml</value>  
  46.         </property>  
  47.         <property name="hibernateProperties">  
  48.             <props>  
  49.                 <prop key="hibernate.show_sql">true</prop>  
  50.             </props>  
  51.         </property>  
  52.     </bean>  
  53. </beans>  

 

 

 

 

struts.xml:

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5. <struts>  
  6.     <constant name="struts.enable.DynamicMethodInvocation" value="true" />  
  7.     <constant name="struts.devMode" value="true" />  
  8.         <!-- 自定义package,在里面加入拦截器栈,注意最后要加上默认拦截器栈,并将自定义的拦截器栈作为默认的拦截器栈,后面的package直接继承该package即可实现所有action加入拦截功能 -->  
  9.         <package name="mypackage" extends="struts-default">  
  10.         <interceptors>  
  11.              <interceptor name="checkLogin" class="checkLogin"></interceptor>  
  12.              <interceptor-stack name="myStack">  
  13.                   <interceptor-ref name="checkLogin"/>  
  14.                   <interceptor-ref name="defaultStack"/>  
  15.              </interceptor-stack>  
  16.         </interceptors>  
  17.         <default-interceptor-ref name="myStack"/>  
  18.     </package>  
  19.     <package name="default" namespace="/" extends="mypackage">  
  20.         <default-action-ref name="index" />  
  21.         <global-results>  
  22.             <result name="error">/error.jsp</result>  
  23.         </global-results>  
  24.         <global-exception-mappings>  
  25.             <exception-mapping exception="java.lang.Exception"  
  26.                 result="error" />  
  27.         </global-exception-mappings>  
  28.         <action name="show" class="userAction" method="select">  
  29.             <result>/WEB-INF/pages/User.jsp</result>  
  30.         </action>  
  31.         <action name="goEdit" class="userAction" method="goEdit">  
  32.             <result>/WEB-INF/pages/editUser.jsp</result>  
  33.         </action>  
  34.         <!-- 使用通配符 -->  
  35.         <action name="*User" class="userAction" method="{1}User">  
  36.             <result type="redirectAction">  
  37.                 <param name="actionName">show</param>  
  38.                 <param name="namespace">/</param>  
  39.             </result>  
  40.         </action>  
  41.     </package>  
  42. </struts>  

 

拦截器:

Java代码  收藏代码
  1. package com.tch.test.ssh.interceptor;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpSession;  
  7.   
  8. import org.apache.struts2.StrutsStatics;  
  9. import org.springframework.stereotype.Component;  
  10.   
  11. import com.opensymphony.xwork2.ActionContext;  
  12. import com.opensymphony.xwork2.ActionInvocation;  
  13. import com.opensymphony.xwork2.interceptor.Interceptor;  
  14. import com.tch.test.ssh.entity.User;  
  15. import com.tch.test.ssh.info.LoginInfo;  
  16. import com.tch.test.ssh.info.UserInfo;  
  17.   
  18. @Component("checkLogin")  
  19. public class CheckLoginInterceptor implements Interceptor {  
  20.     private static final long serialVersionUID = 1L;  
  21.   
  22.     public CheckLoginInterceptor(){  
  23.         System.out.println("CheckLoginInterceptor拦截器创建");  
  24.     }  
  25.       
  26.     @Override  
  27.     public String intercept(ActionInvocation invocation) throws Exception {  
  28.         System.out.println("interceptor............................");  
  29.         HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);    
  30.         String url = request.getRequestURI();  
  31.         if(url.contains("/ssh/login.action")){  
  32.             //登陆  
  33.             return invocation.invoke();  
  34.         }  
  35.         //已经登陆  
  36.         HttpSession session = request.getSession();  
  37.         Date current_login_time = (Date) session.getAttribute("login_time");  
  38.         User user = (User) session.getAttribute("login_user");  
  39.         if(user == null || user.getId() == null || current_login_time == null){  
  40.             //session中没有相关信息,则重新登录  
  41.             return "login";  
  42.         }  
  43.         LoginInfo info = (LoginInfo)UserInfo.LOGIN_USERS.get(user.getId());  
  44.         if(info != null && info.getLoginTime() != null){  
  45.             Date latest_login_time = info.getLoginTime();  
  46.             if(latest_login_time.getTime() > current_login_time.getTime()){  
  47.                 ActionContext.getContext().put("errorMessage""账号在别处登录,当前用户被强制退出 !");  
  48.                 session.invalidate();  
  49.                 System.out.println("*****************删除session*************");  
  50.                 return "error";  
  51.             }  
  52.         }  
  53.         return invocation.invoke();  
  54.     }  
  55.   
  56.     @Override  
  57.     public void destroy() {  
  58.     }  
  59.   
  60.     @Override  
  61.     public void init() {  
  62.     }  
  63. }  

  

 

 

 

action:

 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.web.action;  
  2.   
  3. import java.util.List;  
  4. import java.util.Set;  
  5.   
  6. import javax.annotation.Resource;  
  7.   
  8. import org.springframework.context.annotation.Scope;  
  9. import org.springframework.stereotype.Component;  
  10.   
  11. import com.opensymphony.xwork2.ActionSupport;  
  12. import com.tch.test.ssh.entity.Priority;  
  13. import com.tch.test.ssh.entity.User;  
  14. import com.tch.test.ssh.service.IPriorityService;  
  15. import com.tch.test.ssh.service.IUserService;  
  16.   
  17. @Component("userAction")  
  18. @Scope("prototype")  
  19. public class UserAction extends ActionSupport {  
  20.     private static final long serialVersionUID = 1L;  
  21.       
  22.     private User user;  
  23.     private List<Priority> priorities;  
  24.       
  25.     @Resource(name="userService")  
  26.     private IUserService userService;  
  27.     @Resource(name="priorityService")  
  28.     private IPriorityService priorityService;  
  29.       
  30.     private List<User> users;  
  31.     private List<String> priorityName;  
  32.   
  33.     public List<String> getPriorityName() {  
  34.         return priorityName;  
  35.     }  
  36.   
  37.     public void setPriorityName(List<String> priorityName) {  
  38.         this.priorityName = priorityName;  
  39.     }  
  40.   
  41.     public String select() throws Exception{  
  42.         users = userService.select();  
  43.         System.out.println("所有用户数:"+users.size());  
  44.         return "success";  
  45.     }  
  46.       
  47.     public String addUser() throws Exception{  
  48.         System.out.println("add ..  "+user);  
  49.         userService.add(user);  
  50.         return "success";  
  51.     }  
  52.     public String goEdit() throws Exception{  
  53.         user = userService.getUserById(user.getId());  
  54.         priorities = priorityService.getPriorityByUserId(user.getId());  
  55.         System.out.println(user);  
  56.         return "success";  
  57.     }  
  58.     /** 
  59.      * 删除用户 
  60.      * @return 
  61.      * @throws Exception 
  62.      */  
  63.     public String deleteUser() throws Exception{  
  64.         userService.deleteUser(user.getId());  
  65.         return "success";  
  66.     }  
  67.     /** 
  68.      * 修改用户信息 
  69.      * @return 
  70.      * @throws Exception 
  71.      */  
  72.     public String editUser() throws Exception{  
  73.         try {  
  74.             Set<Priority> priorities = priorityService.getPrioritiesByNames(priorityName);  
  75.             user.setPriorities(priorities);  
  76.             userService.editUser(user);  
  77.         } catch (Exception e) {  
  78.             e.printStackTrace();  
  79.         }  
  80.         return "success";  
  81.     }  
  82.   
  83.     public User getUser() {  
  84.         return user;  
  85.     }  
  86.   
  87.     public void setUser(User user) {  
  88.         this.user = user;  
  89.     }  
  90.   
  91.   
  92.     public List<Priority> getPriorities() {  
  93.         return priorities;  
  94.     }  
  95.   
  96.     public void setPriorities(List<Priority> priorities) {  
  97.         this.priorities = priorities;  
  98.     }  
  99.   
  100.     public List<User> getUsers() {  
  101.         return users;  
  102.     }  
  103.   
  104.     public void setUsers(List<User> users) {  
  105.         this.users = users;  
  106.     }  
  107.       
  108. }  

 service接口:

 

Java代码  收藏代码
  1. package com.tch.test.ssh.service;  
  2.   
  3. import java.util.List;  
  4. import java.util.Set;  
  5.   
  6. import com.tch.test.ssh.entity.Priority;  
  7.   
  8. public interface IPriorityService {  
  9.   
  10.     /** 
  11.      * 根据id获取user对象 
  12.      * @param id 
  13.      * @return 
  14.      */  
  15.     List<Priority> getPriorityByUserId(Integer id) throws Exception;  
  16.     /** 
  17.      * 根据id获取实体对象 
  18.      * @param id 
  19.      * @return 
  20.      */  
  21.     Priority getEntity(Integer id) throws Exception;  
  22.     /** 
  23.      * 根据name获取实体对象 
  24.      * @param id 
  25.      * @return 
  26.      */  
  27.     Set<Priority> getPrioritiesByNames(List<String> names) throws Exception;  
  28.     /** 
  29.      * 测试事务 
  30.      * @throws Exception 
  31.      */  
  32.     void testTransaction() throws Exception;  
  33. }  

 

 

 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.tch.test.ssh.entity.User;  
  6.   
  7. public interface IUserService {  
  8.     /** 
  9.      * 测试事务特性 
  10.      */  
  11.     void testTransaction() throws Exception;  
  12.     /** 
  13.      * 添加user对象 
  14.      * @param id 
  15.      * @return 
  16.      */  
  17.     void add(User user) throws Exception;  
  18.     /** 
  19.      * 查询所有user对象 
  20.      * @param id 
  21.      * @return 
  22.      */  
  23.     List<User> select() throws Exception;  
  24.     /** 
  25.      * 根据id获取user对象 
  26.      * @param id 
  27.      * @return 
  28.      */  
  29.     User getUserById(Integer id) throws Exception;  
  30.   
  31.     /** 
  32.      * 根据id获取user对象 
  33.      * @param id 
  34.      * @return 
  35.      */  
  36.     void editUser(User user) throws Exception;  
  37.     /** 
  38.      * 根据id获取实体对象 
  39.      * @param id 
  40.      * @return 
  41.      */  
  42.     User getEntity(Integer id) throws Exception;  
  43.     /** 
  44.      * 删除用户 
  45.      * @param id 
  46.      */  
  47.     void deleteUser(Integer id) throws Exception;  
  48. }  

 

 

service实现类:

 

Java代码  收藏代码
  1. package com.tch.test.ssh.service;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.List;  
  5. import java.util.Set;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.springframework.stereotype.Service;  
  10. import org.springframework.transaction.annotation.Propagation;  
  11. import org.springframework.transaction.annotation.Transactional;  
  12.   
  13. import com.tch.test.ssh.dao.IPriorityDao;  
  14. import com.tch.test.ssh.entity.Priority;  
  15.   
  16. @Service("priorityService")  
  17. public class PriorityServiceImpl implements IPriorityService {  
  18.   
  19.     @Resource(name="priorityDao")  
  20.     private IPriorityDao priorityDao;  
  21.   
  22.     @Override  
  23.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  24.     public List<Priority> getPriorityByUserId(Integer id) throws Exception{  
  25.         return priorityDao.getPriorityByUserId(id);  
  26.     }  
  27.   
  28.     @Override  
  29.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  30.     public Priority getEntity(Integer id) throws Exception {  
  31.         return priorityDao.getEntity(id);  
  32.     }  
  33.   
  34.     @Override  
  35.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  36.     public void testTransaction() throws Exception {  
  37.         Priority p = new Priority();  
  38.         p.setName("测试");  
  39.         priorityDao.add(p);  
  40.         boolean b=true;  
  41.         if(b){  
  42.             throw new Exception("priority 抛出异常。。。。");  
  43.         }  
  44.     }  
  45.   
  46.     @Override  
  47.     public Set<Priority> getPrioritiesByNames(List<String> names) throws Exception {  
  48.         Set<Priority> priorities = new HashSet<Priority>();  
  49.         if(names == null || names.size() <= 0){  
  50.             return null;  
  51.         }  
  52.         Priority p = null;  
  53.         for(String name:names){  
  54.             p = priorityDao.getPriorityByName(name);  
  55.             priorities.add(p);  
  56.         }  
  57.         return priorities;  
  58.     }  
  59.       
  60.       
  61.   
  62. }  

 

 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.springframework.stereotype.Service;  
  8. import org.springframework.transaction.annotation.Propagation;  
  9. import org.springframework.transaction.annotation.Transactional;  
  10.   
  11. import com.tch.test.ssh.dao.IUserDao;  
  12. import com.tch.test.ssh.entity.User;  
  13.   
  14. @Service("userService")  
  15. @Transactional(propagation=Propagation.REQUIRED)  
  16. public class UserServiceImpl implements IUserService {  
  17.   
  18.     @Resource(name="userDao")  
  19.     private IUserDao userDao;  
  20.       
  21.     @Override  
  22.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  23.     public void add(User user) throws Exception {  
  24.         userDao.add(user);  
  25.     }  
  26.   
  27.     @Override  
  28.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  29.     public void editUser(User user)  throws Exception{  
  30.         userDao.editUser(user);  
  31.     }  
  32.   
  33.     @Override  
  34.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  35.     public User getUserById(Integer id) throws Exception {  
  36.         return userDao.getUserById(id);  
  37.     }  
  38.   
  39.     @Override  
  40.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  41.     public List<User> select() throws Exception {  
  42.         return userDao.select();  
  43.     }  
  44.   
  45.     @Override  
  46.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  47.     public User getEntity(Integer id) throws Exception {  
  48.         return userDao.getEntity(id);  
  49.     }  
  50.   
  51.     @Override  
  52.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  53.     public void testTransaction() throws Exception {  
  54.         User user = new User();  
  55.         user.setName("test");  
  56.         user.setPassword("password");  
  57.         userDao.add(user);  
  58.         boolean b=true;  
  59.         if(b){  
  60.             throw new Exception("priority 抛出异常。。。。");  
  61.         }  
  62.     }  
  63.   
  64.     @Override  
  65.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  66.     public void deleteUser(Integer id) throws Exception {  
  67.         userDao.delete(userDao.getEntity(id));        
  68.     }  
  69.   
  70. }  

 

 

 

 

dao:

 

首先是dao基础接口

 

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. public interface BaseDao<E, PK extends Serializable> {  
  7.     /** 
  8.      *  CreaEed on 2013-9-16  
  9.      * <p>DiscripEion:保存对象</p> 
  10.      * @reEurn void 
  11.      */  
  12.     void save(E entity);  
  13.     /** 
  14.      *  CreaEed on 2013-9-16  
  15.      * <p>DiscripEion:更新对象</p> 
  16.      * @reEurn void 
  17.      */  
  18.     void update(E entity);  
  19.     /** 
  20.      *  CreaEed on 2013-9-16  
  21.      * <p>DiscripEion:删除对象</p> 
  22.      * @reEurn void 
  23.      */  
  24.     void delete(E entity);  
  25.     /** 
  26.      *  CreaEed on 2013-9-16  
  27.      * <p>DiscripEion:根据id查询对象</p> 
  28.      * @reEurn void 
  29.      */  
  30.     E get(Serializable id);  
  31.     /** 
  32.      *  CreaEed on 2013-9-16  
  33.      * <p>DiscripEion:查询全部对象</p> 
  34.      * @reEurn void 
  35.      */  
  36.     List<E> getAll();  
  37.       
  38. }  

 

 

dao基础实现类:

 

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.lang.reflect.ParameterizedType;  
  5. import java.util.List;  
  6.   
  7. public class BaseDaoImpl<E, PK extends Serializable> extends CommomDao implements BaseDao<E,PK>{  
  8.   
  9.     private Class<E> clazz;  
  10.       
  11.     @SuppressWarnings("unchecked")  
  12.     public BaseDaoImpl(){  
  13.         this.clazz = (Class<E>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];  
  14.     }  
  15.       
  16.     @Override  
  17.     public void delete(E entity) {  
  18.         getHibernateTemplate().delete(entity);  
  19.     }  
  20.   
  21.     @SuppressWarnings("unchecked")  
  22.     @Override  
  23.     public E get(Serializable id) {  
  24.         return (E)getHibernateTemplate().get(clazz, id);  
  25.     }  
  26.   
  27.     @SuppressWarnings("unchecked")  
  28.     @Override  
  29.     public List<E> getAll() {  
  30.         return getHibernateTemplate().loadAll(clazz);  
  31.         /*String hql = "from "+clazz.getName(); 
  32.         System.out.println("hql: "+hql); 
  33.         return getSession().createQuery(hql).list();*/  
  34.     }  
  35.   
  36.     @Override  
  37.     public void save(E entity) {  
  38.         getHibernateTemplate().save(entity);  
  39.     }  
  40.   
  41.     @Override  
  42.     public void update(E entity) {  
  43.         getHibernateTemplate().update(entity);  
  44.     }  
  45.   
  46. }  

 

dao接口的demo:

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import com.tch.test.ssh.entity.MyTime;  
  4.   
  5. public interface TimeDao extends BaseDao<MyTime, Integer>{  
  6.   
  7.       
  8. }  

 dao实现类的demo:

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import org.springframework.stereotype.Repository;  
  4.   
  5. import com.tch.test.ssh.entity.MyTime;  
  6. @Repository("TimeDao")  
  7. public class TimerDaoImpl extends BaseDaoImpl<MyTime, Integer> implements TimeDao{  
  8.   
  9. }  

 

 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.hibernate.SessionFactory;  
  6. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  7.   
  8. public class CommomDao extends HibernateDaoSupport{  
  9.   
  10.     @Resource(name="sessionFactory")  
  11.     public void setSuperSessionFactory(SessionFactory sessionFactory){  
  12.         this.setSessionFactory(sessionFactory);  
  13.     }  
  14.       
  15. }  

 

 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.tch.test.ssh.entity.Priority;  
  6.   
  7. public interface IPriorityDao {  
  8.     /** 
  9.      * 根据id获取user对象 
  10.      * @param id 
  11.      * @return 
  12.      */  
  13.     List<Priority> getPriorityByUserId(Integer id) throws Exception;  
  14.     /** 
  15.      * 添加user对象 
  16.      * @param id 
  17.      * @return 
  18.      */  
  19.     void add(Priority user) throws Exception;  
  20.     /** 
  21.      * 根据id获取实体对象 
  22.      * @param id 
  23.      * @return 
  24.      */  
  25.     Priority getEntity(Integer id) throws Exception;  
  26.     /** 
  27.      * 删除对象 
  28.      * @param user 
  29.      * @throws Exception 
  30.      */  
  31.     void delete(Priority user) throws Exception;  
  32.     /** 
  33.      * 更新对象 
  34.      * @param user 
  35.      * @throws Exception 
  36.      */  
  37.     void update(Priority user) throws Exception;  
  38.     /** 
  39.      * 根据name获取实体对象 
  40.      * @param id 
  41.      * @return 
  42.      */  
  43.     Priority getPriorityByName(String name) throws Exception;  
  44. }  

 

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.tch.test.ssh.entity.User;  
  6.   
  7. public interface IUserDao {  
  8.   
  9.     /** 
  10.      * 添加user对象 
  11.      * @param id 
  12.      * @return 
  13.      */  
  14.     void add(User user) throws Exception;  
  15.     /** 
  16.      * 查询所有user对象 
  17.      * @param id 
  18.      * @return 
  19.      */  
  20.     List<User> select() throws Exception;  
  21.     /** 
  22.      * 根据id获取user对象 
  23.      * @param id 
  24.      * @return 
  25.      */  
  26.     User getUserById(Integer id) throws Exception;  
  27.   
  28.     /** 
  29.      * 根据id获取user对象 
  30.      * @param id 
  31.      * @return 
  32.      */  
  33.     void editUser(User user) throws Exception;  
  34.       
  35.     /** 
  36.      * 根据id获取实体对象 
  37.      * @param id 
  38.      * @return 
  39.      */  
  40.     User getEntity(Integer id) throws Exception;  
  41.     /** 
  42.      * 删除对象 
  43.      * @param user 
  44.      * @throws Exception 
  45.      */  
  46.     void delete(User user) throws Exception;  
  47.     /** 
  48.      * 更新对象 
  49.      * @param user 
  50.      * @throws Exception 
  51.      */  
  52.     void update(User user) throws Exception;  
  53.     /** 
  54.      * 测试事务 
  55.      */  
  56.     void testTransaction() throws Exception;  
  57. }  

 

 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.springframework.stereotype.Repository;  
  7.   
  8. import com.tch.test.ssh.entity.Priority;  
  9.   
  10. @Repository("priorityDao")  
  11. public class PriorityDaoImpl extends CommomDao implements IPriorityDao {  
  12.   
  13.     /** 
  14.      * 根据用户id查询用户权限 
  15.      * @param id 
  16.      * @return 
  17.      */  
  18.     @SuppressWarnings("unchecked")  
  19.     @Override  
  20.     public List<Priority> getPriorityByUserId(Integer id) throws Exception {  
  21.         List<Priority> priorities = new ArrayList<Priority>();  
  22.         String sql = " select p.id,p.name from User u , Priority p , User_Priority up where u.id = :id and u.id = up.userId and p.id = up.priorityId ";  
  23.         List<Object[]> result = getSessionFactory().getCurrentSession().createSQLQuery(sql).setInteger("id", id).list();  
  24.         if(result != null && result.size()>0){  
  25.             Priority temp = null;  
  26.             for(Object[] obj:result){  
  27.                 temp = new Priority();  
  28.                 temp.setId(Integer.parseInt(obj[0].toString()));  
  29.                 temp.setName(obj[1].toString());  
  30.                 priorities.add(temp);  
  31.             }  
  32.         }  
  33.         return priorities;  
  34.     }  
  35.   
  36.     @Override  
  37.     public Priority getEntity(Integer id) throws Exception {  
  38.         return (Priority) getHibernateTemplate().get(Priority.class, id);  
  39.     }  
  40.   
  41.     @Override  
  42.     public void delete(Priority user) throws Exception {  
  43.         getHibernateTemplate().delete(user);  
  44.     }  
  45.   
  46.     @Override  
  47.     public void update(Priority user) throws Exception {  
  48.         getHibernateTemplate().update(user);  
  49.     }  
  50.   
  51.     @Override  
  52.     public void add(Priority user) throws Exception {  
  53.         getHibernateTemplate().save(user);  
  54.     }  
  55.   
  56.     @Override  
  57.     public Priority getPriorityByName(String name) throws Exception {  
  58.         return (Priority) getSession().createQuery(" from Priority where name = :name").setString("name", name).uniqueResult();  
  59.     }  
  60.   
  61. }  

 

Java代码  收藏代码
  1. package com.tch.test.ssh.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.stereotype.Repository;  
  6. import org.springframework.transaction.annotation.Propagation;  
  7. import org.springframework.transaction.annotation.Transactional;  
  8.   
  9. import com.tch.test.ssh.entity.User;  
  10.   
  11. @Repository("userDao")  
  12. public class UserDaoImpl extends CommomDao implements IUserDao{  
  13.       
  14.     @Override  
  15.     public void add(User user) throws Exception{  
  16.         getSession().save(user);  
  17.     }  
  18.     @SuppressWarnings("unchecked")  
  19.     @Override  
  20.     public List<User> select() throws Exception{  
  21.         return getSessionFactory().openSession().createQuery(" from User").list();  
  22.     }  
  23.   
  24.       
  25.       
  26.     /** 
  27.      * 根据id获取user对象 
  28.      * @param id 
  29.      * @return 
  30.      */  
  31.     @Override  
  32.     public User getUserById(Integer id) throws Exception {  
  33.         System.out.println("id: "+id);  
  34.         return (User) getSession().createQuery(" from User where id = "+id).uniqueResult();  
  35.     }  
  36.       
  37.     /** 
  38.      * 修改用户权限 
  39.      * @param id 
  40.      * @param priorities 
  41.      */  
  42.     @Override  
  43.     public void editUser(User user)  throws Exception{  
  44.         getHibernateTemplate().saveOrUpdate(user);  
  45.     }  
  46.     @Override  
  47.     public User getEntity(Integer id) throws Exception {  
  48.         return (User) getHibernateTemplate().get(User.class, id);  
  49.     }  
  50.     @Override  
  51.     public void delete(User user) throws Exception {  
  52.         getHibernateTemplate().delete(user);          
  53.     }  
  54.     @Override  
  55.     public void update(User user) throws Exception {  
  56.         getHibernateTemplate().update(user);          
  57.     }  
  58.     @Override  
  59.     @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)  
  60.     public void testTransaction() throws Exception {  
  61.         User user = new User();  
  62.         user.setName("test");  
  63.         user.setPassword("password");  
  64.         add(user);  
  65.         boolean b=true;  
  66.         if(b){  
  67.             throw new Exception("priority 抛出异常。。。。");  
  68.         }  
  69.     }  
  70.   
  71. }  

 

 

 

 

 

实体类:Priority.java 

 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.entity;  
  2.   
  3. import java.util.Set;  
  4.   
  5. /** 
  6.  * Priority entity. @author MyEclipse Persistence Tools 
  7.  */  
  8.   
  9. public class Priority implements java.io.Serializable {  
  10.   
  11.     // Fields  
  12.     private static final long serialVersionUID = 1L;  
  13.     private Integer id;  
  14.     private String name;  
  15.     private Set<User> users;  
  16.   
  17.     // Constructors  
  18.   
  19.     /** default constructor */  
  20.     public Priority() {  
  21.     }  
  22.   
  23.     @Override  
  24.     public String toString() {  
  25.         return "Priority [id=" + id + ", name=" + name + "]";  
  26.     }  
  27.   
  28.     /** full constructor */  
  29.     public Priority(String name) {  
  30.         this.name = name;  
  31.     }  
  32.   
  33.     // Property accessors  
  34.   
  35.     public Integer getId() {  
  36.         return this.id;  
  37.     }  
  38.   
  39.     public void setId(Integer id) {  
  40.         this.id = id;  
  41.     }  
  42.   
  43.     public String getName() {  
  44.         return this.name;  
  45.     }  
  46.   
  47.     public Set<User> getUsers() {  
  48.         return users;  
  49.     }  
  50.   
  51.     public void setUsers(Set<User> users) {  
  52.         this.users = users;  
  53.     }  
  54.   
  55.     public void setName(String name) {  
  56.         this.name = name;  
  57.     }  
  58.   
  59. }  

 

 

 User.java 

 

Java代码  收藏代码
  1. package com.tch.test.ssh.entity;  
  2.   
  3. import java.util.Set;  
  4.   
  5. /** 
  6.  * User entity. @author MyEclipse Persistence Tools 
  7.  */  
  8.   
  9. public class User implements java.io.Serializable {  
  10.   
  11.     // Fields  
  12.   
  13.   
  14.     private static final long serialVersionUID = 1L;  
  15.     private Integer id;  
  16.     private String name;  
  17.     private String password;  
  18.     private Set<Priority> priorities;  
  19.   
  20.     // Constructors  
  21.   
  22.     @Override  
  23.     public String toString() {  
  24.         return "User [id=" + id + ", name=" + name + ", password=" + password  
  25.                 + ", priorities=" + priorities + "]";  
  26.     }  
  27.   
  28.     /** default constructor */  
  29.     public User() {  
  30.     }  
  31.   
  32.     /** full constructor */  
  33.     public User(String name, String password) {  
  34.         this.name = name;  
  35.         this.password = password;  
  36.     }  
  37.   
  38.     // Property accessors  
  39.   
  40.     public Integer getId() {  
  41.         return this.id;  
  42.     }  
  43.   
  44.     public void setId(Integer id) {  
  45.         this.id = id;  
  46.     }  
  47.   
  48.     public String getName() {  
  49.         return this.name;  
  50.     }  
  51.   
  52.     public void setName(String name) {  
  53.         this.name = name;  
  54.     }  
  55.   
  56.     public Set<Priority> getPriorities() {  
  57.         return priorities;  
  58.     }  
  59.   
  60.     public void setPriorities(Set<Priority> priorities) {  
  61.         this.priorities = priorities;  
  62.     }  
  63.   
  64.     public String getPassword() {  
  65.         return this.password;  
  66.     }  
  67.   
  68.     public void setPassword(String password) {  
  69.         this.password = password;  
  70.     }  
  71.   
  72. }  

 映射文件:(没有配置表关联关系):

 User.hbm.xml

 

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--  
  5.     Mapping file autogenerated by MyEclipse Persistence Tools 
  6. -->  
  7. <hibernate-mapping>  
  8.     <class name="com.tch.test.ssh.entity.User" table="user" catalog="test">  
  9.         <id name="id" type="java.lang.Integer">  
  10.             <column name="id" />  
  11.             <generator class="identity" />  
  12.         </id>  
  13.         <property name="name" type="java.lang.String">  
  14.             <column name="name" length="20">  
  15.                 <comment>姓名</comment>  
  16.             </column>  
  17.         </property>  
  18.         <property name="password" type="java.lang.String">  
  19.             <column name="password" length="20">  
  20.                 <comment>密码</comment>  
  21.             </column>  
  22.         </property>  
  23.         <set name="priorities" table="User_Priority" inverse="false">  
  24.             <key column="userId"></key>  
  25.             <many-to-many class="com.tch.test.ssh.entity.Priority"  
  26.                 column="priorityId"></many-to-many>  
  27.         </set>  
  28.     </class>  
  29. </hibernate-mapping>  

 

 Priority.hbm.xml

 

Java代码  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--   
  5.     Mapping file autogenerated by MyEclipse Persistence Tools  
  6. -->  
  7. <hibernate-mapping>  
  8.     <class name="com.tch.test.ssh.entity.Priority" table="priority" catalog="test">  
  9.         <id name="id" type="java.lang.Integer">  
  10.             <column name="id" />  
  11.             <generator class="identity" />  
  12.         </id>  
  13.         <property name="name" type="java.lang.String">  
  14.             <column name="name" length="20">  
  15.                 <comment>模块名</comment>  
  16.             </column>  
  17.         </property>  
  18.         <set name="users" table="User_Priority" inverse="true">  
  19.             <key column="priorityId"></key>  
  20.             <many-to-many class="com.tch.test.ssh.entity.User"  
  21.                 column="userId"></many-to-many>  
  22.         </set>  
  23.     </class>  
  24. </hibernate-mapping>  

 

 

 

页面:User.jsp

 

Html代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib uri="/struts-tags"  prefix="s"%>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <title>My JSP 'User.jsp' starting page</title>  
  12.     <meta http-equiv="pragma" content="no-cache">  
  13.     <meta http-equiv="cache-control" content="no-cache">  
  14.     <meta http-equiv="expires" content="0">      
  15.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  16.     <meta http-equiv="description" content="This is my page">  
  17.     <style type="text/css">  
  18.         *{  
  19.             margin:0;  
  20.             padding:0;  
  21.             color:#666;  
  22.         }  
  23.         body{  
  24.             background-color: #fff;  
  25.         }  
  26.         table{  
  27.             margin:20px auto;  
  28.         }  
  29.         a{  
  30.             text-decoration: none;  
  31.             color:red;  
  32.         }  
  33.         tr{  
  34.             height:35px;  
  35.             cursor:pointer;  
  36.         }  
  37.         #_table2{  
  38.             margin-top: 20px;  
  39.         }  
  40.         .detail ._mouseover{  
  41.             background-color:#eee;  
  42.         }  
  43.         input[type='text'],input[type='password']{  
  44.             height:30px;  
  45.             border:1px solid black;  
  46.             background-color: #fff;  
  47.         }  
  48.         ._eventr{  
  49.             background-color:#eee;  
  50.         }  
  51.     </style>  
  52.     <script type="text/javascript" src="<%=request.getContextPath()%>/common/js/jquery.min.js"></script>  
  53.     <script type="text/javascript">  
  54.         $(function(){  
  55.             $("tbody tr").hover(function(){  
  56.                 $(this).addClass('_mouseover');  
  57.             },function(){  
  58.                 $(this).removeClass('_mouseover');  
  59.             });  
  60.         });  
  61.         //添加用户  
  62.         function addUser(){  
  63.             var f = document.forms[0];  
  64.             f.action = "addUser.action";  
  65.             f.submit();  
  66.         }  
  67.         function deleteUser(id,name){  
  68.             var result = confirm("确认删除"+name+"?");  
  69.             if(result){  
  70.                 window.location.href='deleteUser.action?user.id='+id;  
  71.             }  
  72.         }  
  73.     </script>  
  74.   </head>  
  75.   <body>  
  76.       
  77.     <form action="" method="post">  
  78.         <table cellpadding="0" cellspacing="0" border="1" width="60%" align="center" class="detail">  
  79.             <thead>  
  80.                 <tr>  
  81.                     <th width="15%" align="center">id</th>  
  82.                     <th width="15%" align="center">用户名</th>  
  83.                     <th width="15%" align="center">密码</th>  
  84.                     <th width="15%" align="center">操作</th>  
  85.                 </tr>  
  86.             </thead>  
  87.             <tbody>  
  88.                 <s:iterator value="users" status="user">  
  89.                     <tr <s:if test="#user.even">class='_eventr'</s:if>>  
  90.                         <td width="15%" align="center"><s:property value="id"/></td>  
  91.                         <td width="15%" align="center"><s:property value="name"/></td>  
  92.                         <td width="15%" align="center"><s:property value="password"/></td>  
  93.                         <td width="15%" align="center">  
  94.                             <a href="javascript:window.location.href='goEdit.action?user.id=<s:property value='id'/>'">编辑</a>  
  95.                             <a href="javascript:deleteUser(<s:property value='id'/>,'<s:property value='name'/>')">删除</a>  
  96.                         </td>  
  97.                     </tr>  
  98.                 </s:iterator>  
  99.             </tbody>  
  100.         </table>  
  101.         <table cellpadding="0" cellspacing="0" border="0" width="60%" align="center" id="_table2">  
  102.             <tr>  
  103.                 <td colspan="3">用户名:<input type="text" name="user.name">密码:<input type="text" name="user.password"></td>  
  104.                 <td><input type="button" onclick="addUser()" value="添加用户"></td>  
  105.             </tr>  
  106.         </table>  
  107.     </form>  
  108.       
  109.       
  110.   </body>  
  111. </html>  

 

 

editUser.jsp

Html代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib uri="/struts-tags"  prefix="s"%>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <title>My JSP 'User.jsp' starting page</title>  
  12.     <meta http-equiv="pragma" content="no-cache">  
  13.     <meta http-equiv="cache-control" content="no-cache">  
  14.     <meta http-equiv="expires" content="0">      
  15.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  16.     <meta http-equiv="description" content="This is my page">  
  17.     <style type="text/css">  
  18.         *{  
  19.             margin:0;  
  20.             padding:0;  
  21.             color:#666;  
  22.             line-height:30px;  
  23.         }  
  24.         #content{  
  25.             width:500px;  
  26.             margin:30px auto;  
  27.               
  28.         }  
  29.         input[type='checkbox']{  
  30.             margin-top: 2px;  
  31.             margin-left: 10px;  
  32.             margin-right: 10px;  
  33.         }  
  34.         input[type='text'],input[type='password']{  
  35.             height:30px;  
  36.             border:1px solid black;  
  37.             background-color: #fff;  
  38.         }  
  39.         form .priority{  
  40.             float:left  
  41.             margin-left: 20px;  
  42.         }  
  43.     </style>  
  44.   </head>  
  45.   <body>  
  46.     <div id="content">  
  47.     <form action="editUser.action" method="post" name="myform">  
  48.         用户名:<input type="text" value="<s:property value='user.name'/>" name="user.name">  
  49.         密码:<input type="text" value="<s:property value='user.password'/>" name="user.password"><br/>  
  50.         <span class="priority">权限:</span><br/>  
  51.         <input type="checkbox" name="priorityName" value="管理员" <s:if test="'管理员' in priorities.{name}">checked='checked'</s:if>>管理员<br/>  
  52.         <input type="checkbox" name="priorityName" value="程序员"<s:if test="'程序员' in priorities.{name}">checked='checked'</s:if>>程序员<br/>  
  53.         <input type="checkbox" name="priorityName" value="测试员"<s:if test="'测试员' in priorities.{name}">checked='checked'</s:if>>测试员<br/>  
  54.         <input type="checkbox" name="priorityName" value="运维人员"<s:if test="'运维人员' in priorities.{name}">checked='checked'</s:if>>运维人员<br/>  
  55.         <input type="hidden" name="user.id" value="${user.id}">  
  56.         <input type="submit"  value="确认修改">  
  57.     </form>  
  58.     </div>  
  59.   </body>  
  60. </html>  

 

 

log4j.properties:

 

Properties代码  收藏代码
  1. #  
  2. # Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)  
  3. #  
  4. # The five logging levels used by Log are (in order):  
  5. #  
  6. #   1. DEBUG (the least serious)  
  7. #   2. INFO  
  8. #   3. WARN  
  9. #   4. ERROR  
  10. #   5. FATAL (the most serious)  
  11.   
  12.   
  13. # Set root logger level to WARN and append to stdout  
  14. log4j.rootLogger=info, stdout  
  15. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  16. log4j.appender.stdout.Target=System.out  
  17. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  18.   
  19. # Pattern to output the caller's file name and line number.  
  20. log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n  
  21.   
  22. # Print only messages of level ERROR or above in the package noModule.  
  23. log4j.logger.noModule=FATAL  
  24.   
  25. log4j.logger.com.opensymphony.xwork2=info  
  26. log4j.logger.org.apache.struts2=info  

 

 

测试类:

 

Java代码  收藏代码
  1. package com.tch.test.ssh.test;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.junit.Test;  
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.   
  9. import com.tch.test.ssh.entity.Priority;  
  10. import com.tch.test.ssh.entity.User;  
  11.   
  12. public class SpringTest {  
  13.       
  14.     @Test  
  15.     public void testHibernate(){  
  16.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  17.         SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");  
  18.         Session session = sessionFactory.openSession();  
  19.         session.beginTransaction();  
  20.         User u = new User();  
  21.         u.setId(1);  
  22.         u = (User)session.get(User.class1);  
  23.         System.out.println(u.getPriorities());  
  24.         Priority p = (Priority) session.load(Priority.class3);  
  25.         u.getPriorities().add(p);  
  26. //      u.getPriorities().remove(p);  
  27. //      Priority p = new Priority();  
  28. //      p.setId(3);  
  29. //      u.setPriorities(null);  
  30.           
  31.         session.update(u);  
  32.         System.out.println(u.getPriorities());  
  33.         session.getTransaction().commit();  
  34.         session.close();  
  35.     }  
  36.   
  37. }  

 

 

posted on 2013-09-24 08:55  阿O、不拽  阅读(271)  评论(0)    收藏  举报