springmvc+spring3+hibernate4框架简单整合,简单实现增删改查功能

来源:互联网 发布:戈贝尔体测数据 编辑:程序博客网 时间:2024/04/28 06:11

        springmvc+spring3+hibernate4框架整合,实现增删改查功能

                            

 项目开发环境

 1.Eclipse

2.tomcat7.0

3.MySQL

项目的整体架构


所用到的jar包

数据库表

数据库表就不用教大家了,一张表,很简单的,下面是我建好的表


                    

  下面是web.xml的详情信息

    
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:web="http://java.sun.com/xml/ns/javaee" 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_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>json_test</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>login.jsp</welcome-file>  
  6.   </welcome-file-list>  
  7.   <context-param>  
  8.     <param-name>contextConfigLocation</param-name>  
  9.     <param-value>classpath:spring/spring-*.xml</param-value>  
  10.   </context-param>  
  11.   <listener>  
  12.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  13.   </listener>  
  14.   <listener>  
  15.     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  16.   </listener>  
  17.   <servlet>  
  18.     <servlet-name>springMVC</servlet-name>  
  19.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  20.     <init-param>  
  21.       <param-name>contextConfigLocation</param-name>  
  22.       <param-value>classpath:spring/spring-mvc.xml</param-value>  
  23.     </init-param>  
  24.     <load-on-startup>1</load-on-startup>  
  25.   </servlet>  
  26.   <servlet-mapping>  
  27.     <servlet-name>springMVC</servlet-name>  
  28.     <url-pattern>*.do</url-pattern>  
  29.   </servlet-mapping>  
  30.   <filter>  
  31.     <filter-name>encodingFilter</filter-name>  
  32.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  33.     <init-param>  
  34.       <param-name>encoding</param-name>  
  35.       <param-value>UTF-8</param-value>  
  36.     </init-param>  
  37.     <init-param>  
  38.       <param-name>forceEncoding</param-name>  
  39.       <param-value>true</param-value>  
  40.     </init-param>  
  41.   </filter>  
  42.   <filter-mapping>  
  43.     <filter-name>encodingFilter</filter-name>  
  44.     <url-pattern>/*</url-pattern>  
  45.   </filter-mapping>  
  46.   <filter>  
  47.     <filter-name>openSession</filter-name>  
  48.     <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
  49.   </filter>  
  50.   <filter-mapping>  
  51.     <filter-name>openSession</filter-name>  
  52.     <url-pattern>/*</url-pattern>  
  53.   </filter-mapping>  
  54. </web-app>  
  

     

     下面是spring-common.xml的详情信息

     
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.   xmlns:aop="http://www.springframework.org/schema/aop"  
  5.   xmlns:cache="http://www.springframework.org/schema/cache"  
  6.   xmlns:context="http://www.springframework.org/schema/context"  
  7.   xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
  8.   xmlns:jee="http://www.springframework.org/schema/jee"  
  9.   xmlns:jms="http://www.springframework.org/schema/jms"  
  10.   xmlns:lang="http://www.springframework.org/schema/lang"  
  11.   xmlns:mvc="http://www.springframework.org/schema/mvc"  
  12.   xmlns:oxm="http://www.springframework.org/schema/oxm"  
  13.   xmlns:task="http://www.springframework.org/schema/task"  
  14.   xmlns:tx="http://www.springframework.org/schema/tx"  
  15.   xmlns:util="http://www.springframework.org/schema/util"  
  16.   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  17.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  18.     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd  
  19.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  20.     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd  
  21.     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
  22.     http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd  
  23.     http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd  
  24.     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
  25.     http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd  
  26.     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
  27.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  28.     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">  
  29.       
  30.     <!--扫描映射  -->  
  31.     <context:component-scan base-package="ssh"/>  
  32.       
  33.     <!-- 引入property配置文件 -->  
  34.     <context:property-placeholder location="classpath:prop/jdbc.properties"/>  
  35.           
  36.     <!-- 配置数据源 -->  
  37.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >  
  38.         <property name="driverClassName" value="${jdbc.mysql.driverClassName}"></property>  
  39.         <property name="url" value="${jdbc.mysql.url}"></property>  
  40.         <property name="username" value="${jdbc.mysql.username}"></property>  
  41.         <property name="password" value="${jdbc.mysql.password}"></property>  
  42.         <!-- 初始化连接大小  
  43.         <property name="initialSize" value="${jdbc.initialSize}"></property> -->  
  44.         <!-- 连接池最大数量   
  45.         <property name="maxActive" value="${jdbc.maxActive}"></property>-->  
  46.         <!-- 连接池最大空闲 -->  
  47.         <!-- <property name="maxIdle" value="${maxIdle}"></property> -->  
  48.         <!-- 连接池最小空闲   
  49.         <property name="minIdle" value="${jdbc.minIdle}"></property>-->  
  50.         <!-- 获取连接最大等待时间   
  51.         <property name="maxWait" value="${jdbc.maxWait}"></property>-->  
  52.     </bean>  
  53.       
  54.     <!-- 配置SessionFactory -->  
  55.     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  56.         <property name="dataSource" ref="dataSource" />  
  57.         <property name="hibernateProperties">  
  58.             <props>  
  59.                 <prop key="hibernate.dialect">${jdbc.mysql.dialect}</prop>  
  60.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  61.                 <!--是否显示sql语句 我在这里是显示的  -->  
  62.                 <prop key="hibernate.show_sql">true</prop>  
  63.                 <!--格式化显示sql语句  -->  
  64.                 <prop key="hibernate.format_sql">true</prop>  
  65.             </props>  
  66.         </property>  
  67.         <!-- 自动扫描制定位置下的实体进行映射  -->   
  68.         <property name="packagesToScan" value="ssh.entity"/>  
  69.     </bean>  
  70.       
  71.     <!-- 配置一个事务管理器 -->  
  72.     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  73.         <property name="sessionFactory" ref="sessionFactory"/>  
  74.     </bean>  
  75.       
  76.     <!-- 应该是开启事物 -->  
  77.     <tx:annotation-driven transaction-manager="transactionManager"/>  
  78.       
  79. </beans>  
       

     下面是spring-mvc.xml的详情信息

            
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.     http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.     http://www.springframework.org/schema/context  
  9.     http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  10.     http://www.springframework.org/schema/mvc  
  11.     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  
  12.       
  13.     <!-- 注解扫描包 -->  
  14.     <context:component-scan base-package="ssh" />  
  15.   
  16.     <!-- 开启注解 -->  
  17.     <mvc:annotation-driven />       
  18.   
  19.     <!-- 定义视图解析器 -->    
  20.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  21.         <property name="prefix" value="/"></property>  
  22.         <property name="suffix" value=".jsp"></property>  
  23.     </bean>  
  24. </beans>  


         

       Hibernate用于连接数据库的小配置文件jdbc.properties的详情信息

  1. # JDBC  
  2. # 设置连接池连接时的数量  
  3. jdbc.initialSize=1  
  4. jdbc.filters=stat  
  5. # 连接池中存在的最小连接数目。连接池中连接数目可以变很少,如果使用了maxAge属性,有些空闲的连接会被关闭因为离它最近一次连接的时间过去太久了。但是,我们看到的打开的连接不会少于minIdle。  
  6. jdbc.minIdle=1  
  7. # 连接数据库的最大连接数。这个属性用来限制连接池中能够打开连接的数量,可以方便数据库做连接容量规划。  
  8. jdbc.maxActive=99  
  9. jdbc.maxWait=1000  
  10. jdbc.minEvictableIdleTimeMillis=300000  
  11. jdbc.poolPreparedStatements=true  
  12. jdbc.maxPoolPreparedStatementPerConnectionSize=50  
  13. jdbc.timeBetweenEvictionRunsMillis=60000  
  14. jdbc.validationQuery=select 1 from dual  
  15.   
  16. jdbc.removeAbandonedTimeout=150    
  17. jdbc.logAbandoned=true  
  18. jdbc.removeAbandoned=true  
  19. jdbc.testOnBorrow=false  
  20. jdbc.testOnReturn=false  
  21.   
  22.   
  23. #ORACLE 数据库连接方式  
  24. #jdbc.oracle.driverClassName=oracle.jdbc.driver.OracleDriver  
  25. #jdbc.oracle.url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl  
  26. #jdbc.oracle.username=wrg  
  27. #jdbc.oracle.password=wrg  
  28. #jdbc.oracle.dialect=org.hibernate.dialect.Oracle10gDialect  
  29.   
  30.   
  31.   
  32. # MYSQL 数据库连接方式  
  33. jdbc.mysql.driverClassName=com.mysql.jdbc.Driver  
  34. jdbc.mysql.url=jdbc:mysql://localhost:3806/springmvc?characterEncoding=UTF-8  
  35. jdbc.mysql.username=root  
  36. jdbc.mysql.password=HZIMS_GP  
  37. jdbc.mysql.dialect=org.hibernate.dialect.MySQL5InnoDBDialect  
  38.   
  39.   
  40. #HIBERNATE  
  41. jdbc.show_sql=false  
  42. jdbc.format_sql=false  
             
           

           下面是log4j.properties日志文件的详情信息

                   
  1. #console log  
  2. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender  
  3. log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout  
  4. log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n  
  5.   
  6.   
  7. #logger  
  8. log4j.logger.org.springframework=DEBUG,CONSOLE  
  9. log4j.logger.org.hibernate=INFO,CONSOLE  
  10. log4j.logger.org.apache=INFO,CONSOLE  
  11.   
  12.   
  13.   
  14. log4j.rootLogger=DEBUG,CONSOLE 
               

                    

创建Entity类User实体



       
  1. package ssh.entity;  
  2. import javax.persistence.Column;  
  3. import javax.persistence.Entity;  
  4. import javax.persistence.GeneratedValue;  
  5. import javax.persistence.Id;  
  6. import javax.persistence.Table;  
  7. import org.hibernate.annotations.GenericGenerator;  
  8. @Entity  
  9. @Table(name="TUSER")  
  10. public class User{    
  11.     @Id  
  12.     @GeneratedValue(generator="id")  
  13.     @GenericGenerator(name = "id",strategy="identity")  
  14.     private Integer id;  
  15.     private String name;  
  16.     private String password;      
  17.     @Column(name="LOGIN_DATE")  
  18.     private String loginDate;  
  19.     public Integer getId() {  
  20.         return id;  
  21.     }  
  22.     public void setId(Integer id) {  
  23.         this.id = id;  
  24.     }  
  25.     public String getName() {  
  26.         return name;  
  27.     }  
  28.     public void setName(String name) {  
  29.         this.name = name;  
  30.     }  
  31.     public String getPassword() {  
  32.         return password;  
  33.     }  
  34.     public void setPassword(String password) {  
  35.         this.password = password;  
  36.     }  
  37.     public String getLoginDate() {  
  38.         return loginDate;  
  39.     }  
  40.     public void setLoginDate(String loginDate) {  
  41.         this.loginDate = loginDate;  
  42.     }  
  43.     @Override  
  44.     public String toString() {  
  45.         return "User [id=" + id + "name=" + name + "password=" + password  
  46.                 + ", loginDate=" + loginDate + "]";  
  47.     }  
  48.       
  49. }  


        

创建Dao层接口


           
[html] view plain copy
  1. package ssh.dao;  
  2. import java.util.List;  
  3. import ssh.entity.User;  
  4. public interface UserDao {  
  5.     //登录  
  6.     User selectUser(User user) throws Exception;  
  7.     //查询所有  
  8.     List<User> getAllUsers() throws Exception;  
  9.     //添加用户  
  10.     void addUser(User user) throws Exception;  
  11.     //删除用户  
  12.     void delUser(Integer id) throws Exception;  
  13.     //修改用户  
  14.     void updateUser(User user) throws Exception;  
  15.     //单个查询  
  16.     User getUser(Integer id) throws Exception ;  
  17. }  

  Dao层接口的实现

         
  1. package ssh.dao;  
  2. import java.util.List;  
  3. import org.hibernate.Query;  
  4. import org.hibernate.Session;  
  5. import org.hibernate.SessionFactory;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Repository;  
  8. import ssh.entity.User;  
  9. @Repository  
  10. @SuppressWarnings("unchecked")  
  11. public class UserDaoImpl implements UserDao {  
  12.     @Autowired  
  13.     private SessionFactory sessionFactory;  
  14.     //登录  
  15.     public User selectUser(User user) throws Exception {  
  16.         Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.name=? and u.password=?");  
  17.         query.setString(0, user.getName());  
  18.         query.setString(1, user.getPassword());  
  19.         List<User> list = query.list();  
  20.         if(list==null||list.size()==0){  
  21.             throw new RuntimeException("查询失败");  
  22.         }  
  23.         return list.get(0);  
  24.     }  
  25.       
  26.     //查询所有  
  27.     public List<User> getAllUsers() throws Exception {  
  28.         Query query = sessionFactory.getCurrentSession().createQuery("from User");  
  29.         List<User> list = query.list();  
  30.         return list;  
  31.     }  
  32.       
  33.     //单个查询  
  34.     public User getUser(Integer id) throws Exception {  
  35.         return (User) sessionFactory.getCurrentSession().createQuery("from User u where u.id ="+id).uniqueResult();  
  36.     }  
  37.   
  38.     //添加用户  
  39.     public void addUser(User user) throws Exception {  
  40.         System.out.println("11111111111111111"+user.getName());  
  41.         sessionFactory.getCurrentSession().save(user);  
  42.     }  
  43.       
  44.     //删除用户  
  45.     public void delUser(Integer id) throws Exception {  
  46.         sessionFactory.getCurrentSession().createQuery("delete User u where u.id="+id).executeUpdate();       
  47.           
  48.     }  
  49.       
  50.     //修改用户  
  51.     public void updateUser(User user) throws Exception {  
  52.          Session session = sessionFactory.getCurrentSession();  
  53.          session.beginTransaction();  
  54.          String hql = ("update User u set u.name = ?,u.password = ?,u.loginDate = ? where u.id = ?");    
  55.          Query query = session.createQuery(hql);  
  56.          query.setParameter(0, user.getName());  
  57.          query.setParameter(1, user.getPassword());  
  58.          query.setParameter(2, user.getLoginDate());  
  59.          query.setParameter(3, user.getId());  
  60.          query.executeUpdate();  
  61.          session.getTransaction().commit();               
  62.     }  
  63. }  


        


                           

创建Service层的接口


                           
[html] view plain copy
  1. package ssh.service;  
  2. import java.util.List;  
  3. import ssh.entity.User;  
  4. public interface UserService {  
  5.     //登录  
  6.     User selectUser(User user ) throws Exception;  
  7.     //查询所有  
  8.     List<User> getAllUsers() throws Exception;  
  9.     //添加用户  
  10.     void addUser(User user) throws Exception;  
  11.     //删除用户  
  12.     void delUser(Integer id) throws Exception;    
  13.     //修改用户  
  14.     void updateUser(User user) throws Exception;      
  15.     //单个查询  
  16.     User getUser(Integer id) throws Exception;  
  17. }  
                
            

         Service层的接口的实现

         

[html] view plain copy
  1. package ssh.service;  
  2. import java.util.List;  
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5. import ssh.dao.UserDao;  
  6. import ssh.entity.User;  
  7. @Service("userService")  
  8. public class UserServiceImpl implements UserService{  
  9.     @Autowired  
  10.     private UserDao userDao;  
  11.     //登录  
  12.     public User selectUser(User user) throws Exception {  
  13.         return userDao.selectUser(user);  
  14.     }  
  15.       
  16.     //单个查询  
  17.     public User getUser(Integer id) throws Exception {  
  18.         return userDao.getUser(id);           
  19.     }    
  20.     //查询所有  
  21.     public List<User> getAllUsers() throws Exception {  
  22.         List<User> users = userDao.getAllUsers();       
  23.         return users;  
  24.     }  
  25.       
  26.     //添加用户  
  27.     public void addUser(User user) throws Exception {  
  28.         userDao.addUser(user);    
  29.     }  
  30.     //删除用户  
  31.       
  32.     public void delUser(Integer id) throws Exception {         
  33.         userDao.delUser(id);  
  34.     }  
  35.     //修改用户  
  36.     public void updateUser(User user) throws Exception {  
  37.         userDao.updateUser(user);         
  38.     }     
  39. }  
                        

控制层Action层的代码如下



                              
  1. package ssh.action;  
  2. import javax.servlet.http.HttpServletRequest;  
  3. import javax.servlet.http.HttpServletResponse;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8. import ssh.entity.User;  
  9. import ssh.path.Path;  
  10. import ssh.service.UserService;  
  11. @Controller  
  12. @RequestMapping(value=Path.USER)  
  13. public class UserAction {     
  14.     @Autowired  
  15.     private UserService userService;  
  16.     @RequestMapping(value=Path.LOGIN_INDEX)  
  17.     public String login(HttpServletRequest request, HttpServletResponse response) throws Exception{  
  18.         return Path.LOGIN_INDEX;  
  19.     }  
  20.           
  21.     @RequestMapping(value=Path.LOGIN_OK,method=RequestMethod.POST)  
  22.     public String loginCheck(User user,HttpServletRequest request, HttpServletResponse response) throws Exception{  
  23.         response.setContentType("text/html;charset=utf-8");  
  24.         User u = userService.selectUser(user);  
  25.         System.out.println("user is ------------------------ "+u);  
  26.         request.setAttribute("user", u);  
  27.         return "redirect:/user/index.do";  
  28.         }  
  29.       
  30.     //单个查询  
  31.     @RequestMapping(value=Path.GET_USER)    
  32.     public String getUser(Integer id,HttpServletRequest request) throws Exception{    
  33.         request.setAttribute("user", userService.getUser(id));    
  34.         return Path.UPDATE_USER;    
  35.     }   
  36.       
  37.     //查询所有  
  38.     @RequestMapping(value=Path.INDEX)  
  39.     public String getAllUsers(HttpServletRequest request) throws Exception{  
  40.         request.setAttribute("userList", userService.getAllUsers());  
  41.         return Path.INDEX;  
  42.     }  
  43.     //添加跳转方法  
  44.     @RequestMapping(value=Path.TO_ADDUSER)    
  45.     public String toAddUser(){    
  46.         return Path.ADD_USER;    
  47.     }         
  48.     //添加用户  
  49.     @RequestMapping(value=Path.ADD_USER)  
  50.     public String addUser(User user,HttpServletRequest request) throws Exception{  
  51.         System.out.println("用户名:======"+user.getName());  
  52.         userService.addUser(user);  
  53.         return "redirect:/user/index.do";  
  54.     }  
  55.       
  56.     //删除用户  
  57.     @RequestMapping(value=Path.DEL_USER)  
  58.     public String delUser(Integer id,HttpServletResponse response) throws Exception{    
  59.         userService.delUser(id);  
  60.         return "redirect:/user/index.do";  
  61.     }    
  62.       
  63.     //更新用户  
  64.     @RequestMapping(value=Path.UPDATE_USER)  
  65.     public String  updateUser(User user,HttpServletRequest request) throws Exception{  
  66.           
  67.         userService.updateUser(user);  
  68.         user = userService .getUser(user.getId());  
  69.         request.setAttribute("user", user);       
  70.         return "redirect:/user/index.do";  
  71.           
  72.     }                     
  73. }  


          

全局路径Path的代码

            
  1. package ssh.path;  
  2. public class Path {  
  3.     public static final String USER = "/user";  
  4.     /**  
  5.      * 登陆  
  6.      */  
  7.     public static final String LOGIN_INDEX = "/login";  
  8.     /**  
  9.      * 登陆成功  
  10.      */  
  11.     public static final String LOGIN_OK = "/loginok";  
  12.       
  13.     /**  
  14.      * 查询所有  
  15.      */  
  16.     public static final String INDEX = "/index";  
  17.     /**  
  18.      * 添加用户  
  19.      */  
  20.     public static final String ADD_USER = "/addUser";  
  21.       
  22.     /**  
  23.      * 跳转添加用户  
  24.      */  
  25.     public static final String TO_ADDUSER = "/toaddUser";  
  26.       
  27.     /**  
  28.      * 删除用户  
  29.      */  
  30.     public static final String DEL_USER = "/delUser";  
  31.       
  32.     /**  
  33.      * 更新用户  
  34.      */  
  35.     public static final String UPDATE_USER = "/updateUser";  
  36.       
  37.     /**  
  38.      * 跳转更新用户  
  39.      */  
  40.     public static final String GET_USER = "/getUser";         
  41. }  

                     

测试类Test的代码

                            
  1. package ssh.test;  
  2. import org.hibernate.SessionFactory;  
  3. import org.junit.Test;  
  4. import org.junit.runner.RunWith;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.test.context.ContextConfiguration;  
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9. import ssh.dao.UserDao;  
  10. import ssh.entity.User;  
  11. import ssh.service.UserService;  
  12. @RunWith(SpringJUnit4ClassRunner.class)  
  13. @ContextConfiguration(locations="classpath:spring/spring-common.xml")  
  14. @Transactional  
  15. /**  
  16.  *   
  17.  * @author hello  
  18.  *  说明:在这里 所有实例化的注解我都使用 @Autowrited (spring通用的)  
  19.  *                            也可以使用 @Resource   (J2EE通用的)  
  20.  *                            两者区别百度  
  21.  */  
  22. public class TestAll {  
  23.     @Autowired  
  24.     private SessionFactory sessionFactory;  
  25.     /**  
  26.      * 测试sessionfactory  
  27.      * 测试时 spring-common 不能存在 事物bean  
  28.      *                        不能存在 事物管理器 bean  
  29.      *                        不能存在dao  
  30.      *                        不能存在service  
  31.      *                        不能存在action  
  32.      * 只是为了防止当其他内容写错时 sessionfactory也开启不了 除非是其他的bean没有错  
  33.      */  
  34.     @Test  
  35.     public void testSf(){  
  36.         System.out.println("测试开启");  
  37.         System.out.println("   sessionfactory = "+sessionFactory);  
  38.         System.out.println("测试完成");  
  39.     }  
  40.     /**  
  41.      * 测试UserDao  
  42.      */  
  43.     @Autowired  
  44.     private UserDao userDao;  
  45.     @Test  
  46.     public void testUserDao() throws Exception{  
  47.         User u = new User();  
  48.         u.setName("admin");  
  49.         u.setPassword("12345678");  
  50.         User user  = userDao.selectUser(u);  
  51.         System.out.println("user is "+user);  
  52.         userDao.addUser(u);  
  53.     }                     
  54.     /**  
  55.      * 测试UserService  
  56.      */  
  57.     @Autowired  
  58.     private UserService userService;  
  59.     @Test  
  60.     public void testUserService() throws Exception{  
  61.         User u = new User();  
  62.         u.setName("admin");  
  63.         u.setPassword("12345678");  
  64.         User user = userService.selectUser(u);  
  65.         System.out.println("user is "+user);  
  66.     }  
  67. }  



   

登录界面login.jsp的代码


       
  1. <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <script type="text/javascript" src="../js/jquery-1.8.3.js"></script>  
  10. <style>   
  11. body{ text-align:center}   
  12. .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}   
  13. /* css注释:为了观察效果设置宽度 边框 高度等样式 */   
  14. </style>   
  15.   <body>  
  16.   <div class="div">  
  17.   <h1>用户登录</h1>  
  18.     <form action="/spring_springmvc_hibernate/user/index.do" method="post">  
  19.         用户名:<input  type="text" name="name" >  
  20.         密码:<input  type="password" name="password">  
  21.         <input type="submit" value="提交" >  
  22.     </form>  
  23.     </div>  
  24.   </body>  
  25. </html>  

                        

查询所有index.jsp页面的代码


           
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"    
  2. pageEncoding="UTF-8"%>    
  3. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
  5. <html>    
  6. <head>  
  7. <%  
  8.     String path = request.getContextPath();  
  9. %>  
  10. <script type="text/javascript" src="<%=path%>/js/jquery-1.9.1.min.js"></script>    
  11. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
  12. <title>Insert title here</title>   
  13. <style>   
  14. body{ text-align:center}   
  15. .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}   
  16. /* css注释:为了观察效果设置宽度 边框 高度等样式 */   
  17. .t{ margin:0 auto; width:600px; height:300px; border:1px solid #F00}   
  18.   
  19. </style>   
  20.   
  21. </head>    
  22. <body>   
  23. <div class="div">     
  24.     <h1><a href="/spring_springmvc_hibernate/user/toaddUser.do">添加用户</a></h1>    
  25.     <table border="1" class="t">    
  26.         <tbody>    
  27.         <tr>    
  28.             <th>姓名</th>    
  29.             <th>密码</th>    
  30.             <th>登录时间</th>  
  31.             <th>操作</th>      
  32.         </tr>    
  33.         <c:if test="${!empty userList }">    
  34.             <c:forEach items="${userList}" var="user">    
  35.                 <tr>    
  36.                     <td>${user.name }</td>   
  37.                     <td>${user.password }</td>    
  38.                     <td>${user.loginDate }</td>    
  39.                     <td>    
  40.                         <a href="/spring_springmvc_hibernate/user/getUser.do?id=${user.id }">编辑</a>    
  41.                         <a href="/spring_springmvc_hibernate/user/delUser.do?id=${user.id }">删除</a>    
  42.                     </td>    
  43.                 </tr>                 
  44.             </c:forEach>    
  45.         </c:if>    
  46.     </tbody>   
  47.    </div>     
  48. </table>    
  49. </body>    
  50. </html>    

       

添加用户addUser.jsp的页面代码

       
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"    
  2. pageEncoding="UTF-8"%>  
  3. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
  5. <html>    
  6. <head>    
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
  8. <title>Insert title here</title>    
  9. <style>   
  10. body{ text-align:center}   
  11. .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}   
  12. /* css注释:为了观察效果设置宽度 边框 高度等样式 */   
  13. </style>   
  14. <script type="text/javascript">    
  15. function addUser(){    
  16.     var form = document.forms[0];    
  17.     form.action = "/spring_springmvc_hibernate/user/addUser.do";    
  18.     form.method="post";    
  19.     form.submit();    
  20. }    
  21. </script>    
  22. </head>    
  23. <body>   
  24. <div class="div">    
  25. <h1>添加用户</h1>    
  26. <form action="" name="userForm">   
  27.   
  28.     姓名:<input type="text" name="name">   
  29.     密码:<input type="text" name="password">   
  30.     时间:<input type="text" name="loginDate">    
  31.     <input type="button" value="添加" onclick="addUser()">    
  32. </form>   
  33. </div>   
  34. </body>    
  35. </html>    

      

更新数据updateUser.jsp的页面代码



                                    
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"    
  2. pageEncoding="UTF-8"%>  
  3. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
  5. <html>    
  6. <head>  
  7. <%  
  8. String path = request.getContextPath();  
  9. %>    
  10. <script type="text/javascript" src="<%=path %>/js/jquery-1.9.1.min.js"></script>    
  11. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
  12. <title>Insert title here</title>  
  13. <style>   
  14. body{ text-align:center}   
  15. .div{ margin:0 auto; width:800px; height:500px; border:1px solid #F00}   
  16. /* css注释:为了观察效果设置宽度 边框 高度等样式 */   
  17. </style>     
  18. </head>    
  19. <body>   
  20. <div class="div">     
  21. <h1>编辑用户</h1>    
  22. <form action="/spring_springmvc_hibernate/user/updateUser.do" name="userForm" method="post">    
  23.   <input type="hidden" name="id" value="${user.id }">    
  24.     姓名:<input type="text" name="name" value="${user.name }">    
  25.     密码:<input type="text" name="password" value="${user.password }">    
  26.     时间:<input type="text" name="loginDate" value="${user.loginDate }">   
  27.     <input type="submit" value="编辑" >    
  28. </form>  
  29. </div>      
  30. </body>    
  31. </html>   







    

                                                                
                                       


































































0 0