【笔记】Spring4框架系列 [ 11 ] 之 SSH 实战

ssh整合简单实现员工管理

【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">

  <!-- struts2配置 -->
  <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> -->

  <!-- 方式二 -->
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/config/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>

【entity】

package com.athl.entity;

public class Admin {
    private int id;
    private String adminName;
    private String pwd;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAdminName() {
        return adminName;
    }
    public void setAdminName(String adminName) {
        this.adminName = adminName;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

}

【*.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="com.athl.entity">
    <class name="Admin" table="ssh_admin">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="adminName" length="20"/>
        <property name="pwd" length="20"/>
    </class>
</hibernate-mapping>
<?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="com.athl.entity">
    <class name="Dept" table="ssh_dept">
        <id name="id" column="deptId">
            <generator class="native"/>
        </id>
        <property name="name" column="deptName"/>
    </class>
</hibernate-mapping>
<?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="com.athl.entity">
    <class name="Employee" table="ssh_employee">
        <id name="id" column="empId">
            <generator class="native"/>
        </id>
        <property name="empName"/>
        <property name="salary"/>
        <!-- 多对一 -->
        <many-to-one name="dept" column="dept_id" class="Dept"/>
    </class>
</hibernate-mapping>

【dao】

【BaseDao】

package com.athl.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.SessionFactory;

import com.athl.dao.IBaseDao;

public class BaseDao<T> implements IBaseDao<T> {

    /* 当前操作的实际的bean类型*/
    private Class<T> clazz;
    /* 获取类名称*/
    private String className;

    /*反射泛型*/
    @SuppressWarnings("unchecked")
    public BaseDao(){
        /*当前运行类父类的参数化类型*/
        Type type = this.getClass().getGenericSuperclass();
        /*转换为参数化类型*/
        ParameterizedType pt = (ParameterizedType)type;
        /*得到实际类型*/
        Type types[] = pt.getActualTypeArguments();
        /*获取实际类型*/
        clazz = (Class<T>)types[0];
        className = clazz.getSimpleName();
    }


    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void save(T t) {
        sessionFactory.getCurrentSession().save(t);
    }

    public void update(T t) {
        sessionFactory.getCurrentSession().update(t);
    }

    public void delete(int id) {
        sessionFactory.getCurrentSession()
        .createQuery("delete from " + className + " where id=?")
        .setParameter(0, id).executeUpdate();

    }

    @SuppressWarnings("unchecked")
    public T findById(int id) {
        return (T) sessionFactory.getCurrentSession().get(clazz, id);
    }

    @SuppressWarnings("unchecked")
    public List<T> getAll() {
        return sessionFactory.getCurrentSession().createQuery("from " + className).list();
    }

}

【AdminDao 】

package com.athl.dao.impl;

import com.athl.dao.IAdminDao;
import com.athl.entity.Admin;

public class AdminDao extends BaseDao<Admin> implements IAdminDao {

    /**
     * 根据管理员信息查询
     * @param admin 管理员对象
     * @return 返回查询后的结果
     */
    public Admin findByAdmin(Admin admin) {
        return (Admin) getSessionFactory().getCurrentSession()
                .createQuery("from Admin where adminName=? and pwd=?")
                .setString(0, admin.getAdminName())
                .setString(1, admin.getPwd())
                .uniqueResult();
    }

}

【service】

【AdminService 】

package com.athl.service.impl;

import com.athl.dao.IAdminDao;
import com.athl.entity.Admin;
import com.athl.service.IAdminService;

public class AdminService implements IAdminService {

    /*注入dao (这里一定要用接口接收)*/
    private IAdminDao adminDao; 

    public void setAdminDao(IAdminDao adminDao) {
        this.adminDao = adminDao;
    }

    public void register(Admin admin) {
        adminDao.save(admin);
    }

    public Admin login(Admin admin) {
        return adminDao.findByAdmin(admin);
    }

}

【action】

package com.athl.action;

import com.athl.entity.Admin;
import com.athl.service.IAdminService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 管理员登陆注册模块
 * 1. 登陆
 *
 */
public class AdminAction extends ActionSupport implements ModelDriven<Admin> {

    private static final long serialVersionUID = 1L;
    /*封装请求数据*/
    private Admin admin;
    public Admin getModel() {
        if(admin==null){
            admin=new Admin();
        }
        return admin;
    }

    public Admin getAdmin() {
        return admin;
    }

    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

    /*注入Service*/
    private IAdminService adminService;
    public void setAdminService(IAdminService adminService) {
        this.adminService = adminService;
    }

    /**
     * 登陆
     */
    public String login(){
        // 登陆验证
        Admin adminInfo = adminService.login(admin);
        // 验证
        if (adminInfo == null){
            // 登陆失败
            return "loginFaild";
        } else {
            // 登陆成功, 保存数据到session
            ActionContext.getContext().getSession().put("adminInfo", adminInfo);
            return "index";
        }
    }

}

【拦截器】

package com.athl.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class UserInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = 1L;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // 得到当前执行的方法
        String methodName = invocation.getProxy().getMethod();
        // 得到ActionContext对象
        ActionContext ac = invocation.getInvocationContext();
        // 获取session, 从session中获取登陆的管理员账号
        Object obj = ac.getSession().get("adminInfo");

        // 判断:
        if (!"login".equals(methodName) && !"list".equals(methodName)){

            // 验证
            if (obj == null){
                // 没有登陆
                return "login";
            } else {
                // 执行Action
                return invocation.invoke();
            }

        } else {
            // 允许访问登陆、列表展示
            return invocation.invoke();
        }
    }

}

【applicationContext.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-*.xml"/>
    <!-- <import resource="config/bean-base.xml"/>
    <import resource="config/bean-dao.xml"/>
    <import resource="config/bean-service.xml"/>
    <import resource="config/bean-action.xml"/> -->

</beans>

【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="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
        <property name="initialPoolSize" value="3"/>
        <property name="maxPoolSize" value="6"/>
    </bean>

    <!-- 2. Spring管理SessionFactory (全部配置都写到spring中) -->
    <!-- # 注入DataSource、 注入常用配置属性、映射配置属性 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <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>
        <!-- 映射配置方法一 (指定文件) -->
        <!-- <property name="mappingLocations">
            <list>
                <value>classpath:com/athl/entity/*.hbm.xml</value>
            </list>
        </property> -->
        <!-- 映射配置方法二 (指定目录)-->
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:com/athl/entity/</value>
            </list>
        </property>
    </bean>

    <!-- 3. 事务相关配置 -->
    <!-- 3.1 事务管理器类 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </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(* com.athl.service.impl.*.*(..))" id="pc"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
    </aop:config>

</beans>

【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="com.athl.dao.impl.AdminDao">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="deptDao" class="com.athl.dao.impl.DeptDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <bean id="employeeDao" class="com.athl.dao.impl.EmployeeDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

</beans>

【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">

    <!-- Action中需要注入Service -->  

    <!-- 1. 员工管理模块 -->
    <bean id="employeeAction" class="com.athl.action.EmployeeAction" scope="prototype">
        <property name="employeeService" ref="employeeService"/>
        <property name="deptService" ref="deptService"/>
    </bean>  

    <!-- 2. 管理员模块 -->
    <bean id="adminAction" class="com.athl.action.AdminAction" scope="prototype">
        <property name="adminService" ref="adminService"/>
    </bean>

</beans>

【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" default-autowire="byName">

     <!-- Service 需要注入 Dao --> 

     <bean id="adminService" class="com.athl.service.impl.AdminService">
        <property name="adminDao" ref="adminDao"/>
     </bean>

     <bean id="deptService" class="com.athl.service.impl.DeptService">
         <property name="deptDao" ref="deptDao"/>
    </bean>

    <bean id="employeeService" class="com.athl.service.impl.EmployeeService">
        <property name="employeeDao" ref="employeeDao"/>
    </bean>

</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="person"  extends="struts-default">

        <!-- 拦截器配置 -->
        <interceptors>
            <interceptor name="userInterceptor" class="com.athl.action.UserInterceptor"/>
            <interceptor-stack name="userStack">
                <interceptor-ref name="defaultStack"/>
                <interceptor-ref name="userInterceptor"/>
            </interceptor-stack>
        </interceptors>

        <!-- 执行指定的拦截器 -->
        <default-interceptor-ref name="userStack"/>

        <!-- 全局视图 -->
        <global-results>
            <result name="success">/index.jsp</result>
            <result name="login" type="redirect">/login.jsp</result>

            <!-- 错误视图配置 -->
            <result name="null">/error/null.jsp</result>
            <result name="error">/error/error.jsp</result>
        </global-results>

        <!-- 全局异常 -->
        <global-exception-mappings>

            <!-- result 会取找全局视图的名称 -->
            <exception-mapping result="null" exception="java.lang.NullPointerException"/>
            <exception-mapping result="error" exception="java.lang.Exception"/>
        </global-exception-mappings>

        <!-- Ation实例交给spring容器创建 -->

        <!-- 员工Action -->
        <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>

            <!-- 进入修改页面 -->
            <result name="edit">/WEB-INF/edit.jsp</result>

        </action>

        <!-- 管理员Action -->
        <action name="admin_*" class="adminAction" method="{1}">

            <!-- 登陆失败 -->
            <result name="loginFaild">/login.jsp</result>

            <!-- 登陆成功 -->
            <result name="index" type="redirectAction">emp_list</result>

        </action>

    </package>
</struts>

【jsp】

【index】

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!-- 跳转方式一 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:redirect url="/emp_list.action"/>

<!-- 跳转方式二 -->
<%-- <%response.sendRedirect(request.getContextPath() + "/emp_list.action");%> --%>

源码下载:http://download.csdn.net/detail/jul_11th/9742616

谢谢支持!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值