SSHdemo项目 功能:列表首页展示 新增修改

 

 

 

1·.创建基本表结构并录入数据   

t_employ    t_dept

 

 

2   entity实体包   get ,set方法

public class admin {
private int id;
private String adminname;
private String pwd;
}


public class dept {
private int id;
private String name;
}


public class employee {
private int id;
private String empname;
private double salary;
private dept dept;
}
hibernate 配置文件

admin.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.entity"> <class name="admin" table="t_admin"> <id name="id" > <generator class="native"></generator> </id> <property name="adminname" length="20"></property> <property name="pwd" length="20"></property> </class> </hibernate-mapping>


dept.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.entity"> <class name="dept" table="t_dept"> <id name="id" column="deptid"> <generator class="native"></generator> </id> <property name="name" column="deptname"></property> </class> </hibernate-mapping>


employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.entity"> <class name="employee" table="t_employ"> <id name="id" column="empid"> <generator class="native"></generator> </id> <property name="empname" ></property> <property name="salary"></property> <many-to-one name="dept" column="dept_id" class="dept"></many-to-one> </class> </hibernate-mapping>

 

3.  spring  配置文件  bean-base.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">


<!-- 1. 连接池实例 -->
 <bean id="datasource"  class="com.mchange.v2.c3p0.ComboPooledDataSource" >
       <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="6"></property>
        
 </bean>  


<!-- 2. Spring管理SessionFactory 【全部配置都写到spring中】 -->
    <!-- # 注入DataSource、 注入常用配置属性、映射配置属性 -->
 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- a. 连接池 -->
        <property name="dataSource" ref="datasource"></property>
        
        <!-- b. hibernate常用配置: 方言、显示sql、自动建表等 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        
        <!-- c. 映射配置 -->
        <property name="mappingLocations">
            <list>
                <value>classpath:cn/itcast/entity/*.hbm.xml</value>
            </list>
        </property>

</bean>





<!-- 3. 事务相关配置 -->
    <!-- 3.1 事务管理器类 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
<!-- 3.2 事务增强(如何管理事务)-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
        <tx:method name="get*"  read-only="true"/>
         <tx:method name="find*"  read-only="true"/>
            <tx:method name="*" read-only="false"/>
        </tx:attributes>
    </tx:advice>
    <!-- 3.3 Aop配置 = 切入点表达式(拦截目标对象,生成代理)  + 事务增强应用-->
    <aop:config>
        <aop:pointcut expression="execution(* cn.itcast.service.*.*(..))" id="pt"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>


    
</beans>   

 

4.

dao层      (iadmindao,ideptdao,iemployeedao)

 

dao.impl层  (admindao,deptdao,employeedao)

 

public interface iadmindao {
    void save(admin admin);
    admin findbyadmin(admin admin);
}


public interface  ideptdao {
List<dept> getall();
dept findbyid(int id);
}


public interface iemployeedao {
void save(employee emp);
void update(employee emp);
void delete(int id);
employee findbyid(int id);
List<employee> getall();
List<employee>  getall(String employeename);
}

 

 

public class admindao implements iadmindao{
  private SessionFactory  sessionfactory;
      // IOC容器(依赖)注入SessionFactory对象
    public void setSessionfactory(SessionFactory sessionfactory) {
    this.sessionfactory = sessionfactory;
}

    @Override
    public void save(admin admin) {
        // TODO Auto-generated method stub
     sessionfactory.getCurrentSession().save(admin);
    }

    @Override
    public admin findbyadmin(admin admin) {
        // TODO Auto-generated method stub
        return     (admin)sessionfactory.getCurrentSession()
.createQuery("from admin where adminname=? and pwd=?") .setString(0, admin.getAdminname()).setString(1, admin.getPwd()).uniqueResult(); } }

 

 

public class deptdao  implements ideptdao{

    private SessionFactory  sessionfactory;

    public void setSessionfactory(SessionFactory sessionfactory) {
        this.sessionfactory = sessionfactory;
    }

    @Override
    public List<dept> getall() {
        // TODO Auto-generated method stub
        return sessionfactory.getCurrentSession().createQuery("from dept").list();
    }

    @Override
    public dept findbyid(int id) {
        // TODO Auto-generated method stub
        return (dept) sessionfactory.getCurrentSession().get(dept.class, id);
    }

}
public class employeedao implements iemployeedao{

    private SessionFactory  sessionfactory;
    

    public void setSessionfactory(SessionFactory sessionfactory) {
        this.sessionfactory = sessionfactory;
    }

    @Override
    public void save(employee emp) {
        // TODO Auto-generated method stub
        sessionfactory.getCurrentSession().save(emp);
    }

    @Override
    public void update(employee emp) {
        // TODO Auto-generated method stub
        sessionfactory.getCurrentSession().update(emp);
    }

    @Override
    public void delete(int id) {
        // TODO Auto-generated method stub
        sessionfactory.getCurrentSession()//
        .createQuery("delete from employee where id=?")//
        .setParameter(0, id)//
        .executeUpdate();
    }

    @Override
    public employee findbyid(int id) {
        // TODO Auto-generated method stub
        return (employee) sessionfactory.getCurrentSession().get(employee.class, id);
    }

    
    @SuppressWarnings("unchecked")
    @Override
    public List<employee> getall() {
        // TODO Auto-generated method stub
        return sessionfactory.getCurrentSession().createQuery("from employee").list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<employee> getall(String employeename) {
        // TODO Auto-generated method stub
        return sessionfactory.getCurrentSession()//
                .createQuery("from employee where empname like ?")//
                .setParameter(0, "%" +employeename + "%")//
                .list();
    }

}

 

 

bean-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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- Dao 注入 SessionFactory -->
    <bean id="admindao" class="cn.itcast.dao.impl.admindao" >
        <property name="sessionfactory" ref="sessionFactory"></property>
    </bean>
    <bean id="deptdao" class="cn.itcast.dao.impl.deptdao" >
        <property name="sessionfactory" ref="sessionFactory"></property>
    </bean>
    <bean id="employeedao" class="cn.itcast.dao.impl.employeedao" >
        <property name="sessionfactory" ref="sessionFactory"></property>
    </bean>
</beans>  

 

 

 

5.service层     service.impl层

public interface  iadminservice {
void register(admin admin);
admin login(admin admin);
}


public interface ideptservice {
List<dept> getall();
dept findbyid(int id);

}



public interface iemployeeservice {
    void save(employee emp);

    /**
     * 跟新员工信息
     * @param emp
     */
    void update(employee emp);


    /**
     * 根据主键查询
     * @param id
     * @return
     */
    employee findbyid(int id);

    /**
     * 查询全部
     * @return
     */
    List<employee> getall();

    /**
     * 根据员工名称条件查询
     * @param employeeName
     * @return
     */
    List<employee> getall(String employeename);
    
    /**
     * 根据主键删除
     * @param id
     */
    void delete(int id);
    
    /**
     *  删除多个员工
     */
    void deletemany(int[] ids);

}

 

public class adminservice implements iadminservice {
private   iadmindao admindao;

public void setAdmindao(iadmindao admindao) {
    this.admindao = admindao;
 }

    @Override
    public void register(admin admin) {
        // TODO Auto-generated method stub
           admindao.save(admin);
    }

    @Override
    public admin login(admin admin) {
        // TODO Auto-generated method stub
        return admindao.findbyadmin(admin);
    }

}




public class deptservice implements ideptservice {
private ideptdao deptdao;

    public void setDeptdao(ideptdao deptdao) {
    this.deptdao = deptdao;
}

    @Override
    public List<dept> getall() {
        // TODO Auto-generated method stub
        return deptdao.getall();
    }

    @Override
    public dept findbyid(int id) {
        // TODO Auto-generated method stub
        return deptdao.findbyid(id);
    }

}



public class employeeservice implements iemployeeservice {
private iemployeedao employeedao;

    
    
    
    public void setEmployeedao(iemployeedao employeedao) {
    this.employeedao = employeedao;
}

    @Override
    public void save(employee emp) {
        // TODO Auto-generated method stub
   employeedao.save(emp);
    }

    @Override
    public void update(employee emp) {
        // TODO Auto-generated method stub
        employeedao.update(emp);
    }

    @Override
    public employee findbyid(int id) {
        // TODO Auto-generated method stub
        return employeedao.findbyid(id);
    }

    @Override
    public List<employee> getall() {
        // TODO Auto-generated method stub
        return employeedao.getall();
    }

    @Override
    public List<employee> getall(String employeename) {
        // TODO Auto-generated method stub
        return employeedao.getall(employeename);
    }

    @Override
    public void delete(int id) {
        // TODO Auto-generated method stub
      employeedao.delete(id);
    }

    @Override
    public void deletemany(int[] ids) {
        // TODO Auto-generated method stub
        if (ids != null && ids.length >0) {
            for (int id : ids){
                delete(id);
            }
        }
    }

}

 

 

 

bean-service.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Service 需要注入 Dao -->
    <bean id="adminservice" class="cn.itcast.service.impl.adminservice">
        <property name="admindao" ref="admindao"></property>
    </bean>
    
    <bean id="deptservice" class="cn.itcast.service.impl.deptservice">
        <property name="deptdao" ref="deptdao"></property>
    </bean>
    
    <bean id="employeeservice" class="cn.itcast.service.impl.employeeservice">
        <property name="employeedao" ref="employeedao"></property>
    </bean>
    
</beans>   

 

 

 

6.action层

 

/**
 * 员工模块控制器开发:
 * 1. 员工列表展示
 * 2. 添加员工
 * 3. 修改员工信息
 * 5. 删除
 * 
 *RequestAware  将数据保存到request中   
 *这样不用重复  map<string,object> request=(map<string,object>)actioncontext.getcontext.get("request");
 *
 */
public class employeeaction  extends ActionSupport   implements  ModelDriven<employee>, RequestAware{
/**
 * 模型驱动要布置set get方法
 */
    private int deptid;
    
    public void setDeptid(int deptid) {
        this.deptid = deptid;
    }
    public int getDeptid() {
        return deptid;
    }
    
    /*******一、封装数据
    private Employee employee = new Employee();   // 【模型驱动】
    // 封装请求的部门id(下拉列表的实际的值)
     * 
     * 
     */
    private employee employee= new employee();
    public void setEmployee(employee employee) {
        this.employee = employee;
    }
    public employee getEmployee() {
        return employee;
    }
    @Override
    public employee getModel() {
        // TODO Auto-generated method stub
        return employee;   //返回实例化的对象
    }
    
    

    /*******二、注入员工Service********/
    private iemployeeservice employeeservice;
    
    public void setEmployeeservice(iemployeeservice employeeservice) {
        this.employeeservice = employeeservice;
    }
    
    // 部门Service
    private ideptservice deptservice;
    
    public void setDeptservice(ideptservice deptservice) {
        this.deptservice = deptservice;
    }

    
    /**
     * 1. 员工列表展示
     */
    public String list(){
        List<employee> listemp=employeeservice.getall();
        
        request.put("listemp", listemp);
        return  "list";
    }

    
    /**
     * 添加员工   
     * @return
     */
    
    public String viewadd(){
        // 查询所有部门信息, 保存到request
        List<dept> listdept = deptservice.getall();
        
        request.put("listdept", listdept);
        
        
        return "add";
    }
    
    
    
    /**
     * 2. 添加员工 - 添加员工数据
     */
    public String  save(){
        // 先根据部门主键查询
        dept dept= deptservice.findbyid(deptid);
        employee.setDept(dept);
        // 设置到员工对象中
        employeeservice.save(employee);
        // 调用Service,保存员工
        return "listaction";
        // 重定向到Action
        
        
    
    }
    private  Map<String, Object>request;
    
    @Override
    public void setRequest(Map<String, Object> request) {
        // TODO Auto-generated method stub
        this.request=request;
    }
    
}

 

bean-action.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="employeeaction" class="cn.itcast.action.employeeaction" >
        <property name="employeeservice" ref="employeeservice"></property>
        <property name="deptservice" ref="deptservice"></property>
    </bean>

</beans>   

 

bean.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx.xsd">

    <import resource="config/bean-base.xml"/>
    <import resource="config/bean-dao.xml"/>
    <import resource="config/bean-action.xml"/>
    <import resource="config/bean-service.xml"/>
</beans>  

 

 

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
    
<struts>
<package name="emp"  extends="struts-default">

<global-results>

<result name="success">/index.jsp</result>
<result name="null">/error/null.jsp</result>
<result name="error">/error/error.jsp</result>
</global-results>

<global-exception-mappings>
<exception-mapping  result="null"  exception="java.lang.NullPointerException"  ></exception-mapping>
<exception-mapping  result="error"  exception="java.lang.Exception"  ></exception-mapping>
</global-exception-mappings>


<action name="emp_*"  class="employeeaction" method="{1}">
<result name="list">/WEB-INF/list.jsp</result>
<result name="add">/WEB-INF/add.jsp</result>

<result name="listaction"  type="redirectAction">emp_list</result>


</action>
</package>
</struts>    

 

 

web.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">

    
     <!-- struts  配置信息 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
 <!-- spring  配置信息 -->
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:bean*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    
    <title>用户展示区</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">
    -->
  </head>
  
  <body>
  <div  align="center" style="width:80%">
  <s:a href="emp_viewadd">添加员工</s:a>
  
  </div>
   <table  border="1"  align="center" width="80%"  cellpadding="5" cellspacing="0">
   <tr>
           <th>序号</th>
           <th>员工编号</th>
           <th>员工姓名</th>
           <th>员工薪水</th> 
    </tr>
                <s:if test="#request.listemp != null">
               <s:iterator var="emp" value="#request.listemp" status="st">
                   <tr>
                       <td> <s:property value="#st.count"/> </td>
                       <td> <s:property value="#emp.id"/> </td>
                       <td> <s:property value="#emp.empname"/> </td>
                       <td> <s:property value="#emp.salary"/> </td>
               
                   </tr>
               </s:iterator>
           </s:if>
           <s:else>
               <tr>
                   <td colspan="5">对不起,没有你要找的数据!请先录入。</td>
               </tr>
           </s:else>    
   </table>
  </body>
</html>

 

 

 

add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    
    <title>添加</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">
    -->
  </head>
  
 <body>
 <s:form action="/emp_save.action"  method="post" theme="simple">
<table border="1"  align="center" cellpadding="5"  cellspacing="0">
<tr>
<td> 员工姓名  </td>   
<td>
<s:textfield  name="empname"  id="empname"   value=""></s:textfield>
</td>
</tr>

<tr>
<td>员工薪水  </td>   
<td>
<s:textfield  name="salary"  id="salary"   value=""></s:textfield>
</td>
</tr>
<tr>

<tr>
               <td>选择部门</td>
               <td>
                 <s:select
                         name="deptid" 
                         headerKey="-1"
                         headerValue="请选择"
                         list="#request.listdept"
                         listKey="id"
                         listValue="name"
                         value="-1"
                     ></s:select>
               </td>
</tr>



<tr>
               <td colspan="2">
                   <s:submit value="添加员工"></s:submit>
               </td>
</tr>

</table>
</s:form>
  </body>
</html>

 

 

 

######################################################

遇到过的坑:

myeclipse     tomcat服务器中已有其他项目启动 ,报错提示 其他项目找不到 配置文件。

解决办法 ,删除tomcat  服务器下其他项目配置文件 这样启动项目较快

 

save  增加员工,保存数据就提示找不到empsave.action ,action设置没错 ,就是添加员工添加不了

解决办法,打断点 观察到数据保存不了,在于t_employ表   empid 没设置自动增加属性,empid没值,保存不了。删除外键关联,重新创建empid 列  设为自动增长 。

 

posted @ 2017-12-08 14:50  yimian  阅读(265)  评论(0编辑  收藏  举报
访问人数:AmazingCounters.com