SSH2 整合小测

 本贴为测试帖,用于整合ssh2

Hbm.xml:

    <hibernate-mapping package="cn.clq.bean">

       <class name="Employee" table="employe">

           <id name="id"type="java.lang.Integer">

               <generator class="identity"></generator>

           </id>

          

           <!-- 必须放在主键id后面  用于控制版本号,防止重复(同时提交) 每次提交自动增一 -->

           <version name="var" />

          

           <property name="username" type="java.lang.String">

              <column name="username" length="20"not-null="true"></column>

           </property>

          

           <property name="password" type="java.lang.String">

              <column name="Birthday" length="20"not-null="true"></column>

           </property>

          

           <!-- length为枚举中字符串的最长长度 -->

           <property name="gender" not-null="true"length="5">

                <type name="org.hibernate.type.EnumType">

                   <param name="enumClass">cn.itcast.bean.Gender</param>

    <!-- 12java.sql.Types.VARCHAR常量值,即保存枚举的字面值到数据库。如果不指定type参数,保存枚举的索引值(0开始)到数据库-->

                   <param name="type">12</param>

                </type>

            </property>

       </class>

    </hibernate-mapping>

 

 

Hibernate.cfg.xml:

<hibernate-configuration>

<session-factory>

    <!--在控制台显示SQL语句-->

    <property name="show_sql">true</property>

    <!--根据需要自动生成、更新数据表  update-->

    <property name="hbm2ddl.auto">update</property>

    <property name="hibernate.format_sql">update</property>

    <!--

       <propertyname="connection.useUnicode">true</property>

       <propertyname="connection.characterEncoding">gbk</property>

    -->

 

    <!--注册所有ORM映射文件-->

    <mapping resource="cn/clq/oa/domain/Role.hbm.xml" />

    <mapping resource="cn/clq/oa/domain/Departmant.hbm.xml"/>

    <mapping resource="cn/clq/oa/domain/User.hbm.xml" />

    <mapping resource="cn/clq/oa/domain/Privilege.hbm.xml"/>

    <mapping resource="cn/clq/oa/domain/Forum.hbm.xml" />

    <mapping resource="cn/clq/oa/domain/Reply.hbm.xml" />

    <mapping resource="cn/clq/oa/domain/Topic.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

Jdbc.properties:

jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl

driverClass=oracle.jdbc.driver.OracleDriver

user=scott

password=363346778

 

beans.xml:

   

    <!-- 用于注解注入-->

   <context:annotation-config />

    <context:component-scan base-package="cn.clq.oa"/>

    <!-- 注解AOP开发配置 -->

    <aop:aspectj-autoproxy />

   

    <!-- 导入外部的properties文件 -->

    <context:property-placeholder location="classpath:jdbc.properties"/>

   

    <!-- 配置SessionFactory-->

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

       <!-- 指定hibernate的配置文件位置 -->

       <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

       <!-- 配置c3p0数据库连接池 -->

       <property name="dataSource">

           <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">

              <!-- 数据连接信息 -->

              <property name="jdbcUrl" value="${jdbcUrl}"></property>

              <property name="driverClass" value="${driverClass}"></property>

              <property name="user" value="${user}"></property>

              <property name="password" value="${password}"></property>

              <!-- 其他配置 -->

              <!--初始化时获取三个连接,取值应在minPoolSizemaxPoolSize之间。Default: 3 -->

              <property name="initialPoolSize" value="3"></property>

              <!--连接池中保留的最小连接数。Default: 3 -->

              <property name="minPoolSize" value="3"></property>

              <!--连接池中保留的最大连接数。Default: 15 -->

              <property name="maxPoolSize" value="5"></property>

              <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->

              <property name="acquireIncrement" value="3"></property>

              <!-- 控制数据源内加载的PreparedStatements数量。如果maxStatementsmaxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->

              <property name="maxStatements" value="8"></property>

              <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->

              <property name="maxStatementsPerConnection" value="5"></property>

              <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->

              <property name="maxIdleTime" value="1800"></property>

           </bean>

       </property>

    </bean>

 

    <!-- 配置声明式事务管理(采用注解的方式) -->

    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

       <property name="sessionFactory" ref="sessionFactory"></property>

    </bean>

    <tx:annotation-driven transaction-manager="txManager"/>

   

 

 

Struts.xml:

<struts>

    <!-- 默认的视图主题 -->

   <constant name="struts.ui.theme" value="simple" />

   

    <!-- 使用Spring的对象工厂类替换掉 struct2默认的对象工厂

    <constantname="struts.objectFactory" value="spring" />

    -->

     

    <!-- 配置为开发模式  修改配置后立即生效 -->

    <constant name="struts.devMode" value="true" />

    <!-- 把扩展名修改为action -->

    <constant name="struts.action.extension" value="action"></constant>

   

    <package name="default" namespace="/"extends="struts-default">

       <interceptors>

           <!-- 声明拦截器 -->

           <interceptor name="checkPrivilegeInterceptor" class="cn.clq.oa.util.CheckPrivilegeInterceptor"></interceptor>

           <!-- 重新定义默认拦截器 -->

           <interceptor-stack name="defaultStack">

              <interceptor-ref name="defaultStack"></interceptor-ref>

              <interceptor-ref name="checkPrivilegeInterceptor"></interceptor-ref>

           </interceptor-stack>

       </interceptors>

      

       <!-- 配置全局的reslut -->

       <global-results>

           <result name="noPrivilegeError">/WEB-INF/noPrivilegeError.jsp</result>

           <result name="loginUI">/WEB-INF/jsp/userAction/loginUI.jsp</result>

       </global-results>

                    

       <action name="departmant_*" class="departmantAction" method="{1}">

           <result name="list">/WEB-INF/jsp/DepartmantAction/list.jsp</result>

           <result name="presitUI">/WEB-INF/jsp/DepartmantAction/presitUI.jsp</result>

           <!-- ?后面的 parentId 用于在修改,删除时返回到当前查询列表-->

           <result name ="toList" type="redirectAction">departmant_list?parentId=${parentId}</result>

       </action>

    </package>

</struts>

 

Web.xml:

    <!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 -->

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath:beans.xml</param-value>

    </context-param>

    <!-- Spring容器进行实例化 -->

    <listener>

          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

   

    <!-- 自定义监听器初始化监听   必须配置在Spring 之后  -->

    <listener>

       <listener-class>cn.clq.oa.util.InitListener</listener-class>

    </listener>

   

   

    <!-- 配置Spring的用于解决懒加载问题的过滤器 -->

    <filter>

       <filter-name>OpenSessionInViewFilter</filter-name>

    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>

    </filter>

    <filter-mapping>

       <filter-name>OpenSessionInViewFilter</filter-name>

       <url-pattern>*.action</url-pattern>

    </filter-mapping>

   

   

    <!-- 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>

 

定义拦截器:

public classCheckPrivilegeInterceptor extends AbstractInterceptor {

 

    public Stringintercept(ActionInvocation invocation) throws Exception {

       // 获取信息  -- struts2 环境

       Useruser = (User) ActionContext.getContext().getSession().get("user"); // 当前登录用户

       Stringnamespace = invocation.getProxy().getNamespace();              // 获取命名空间

       StringactionName = invocation.getProxy().getActionName();            // 获取action名字

       StringprivUrl = namespace + actionName; // 对应的权限URL

 

       // 如果未登录

       if (user == null) {

           //  如果不进行判断,则无法获得user,该对象一直为null

           if (privUrl.startsWith("/user_login")){            

           // 如果是去登录,就放行

              return invocation.invoke();

           }else{

              // 如果不是去登录,就转到登录页面

              return "loginUI";

           }

       }

       // 如果已登录,就判断权限

       else {

           if (user.hasPrivilegeByUrl(privUrl)){

              // 如果有权限,就放行

              return invocation.invoke();

           }else{

              // 如果没有权限,就转到提示页面

              return "noPrivilegeError";

           }

       }

    }

}

 

 

监听:

public classInitListener implements ServletContextListener {

 

    public voidcontextInitialized(ServletContextEvent arg0) {

       //  获取容器与相关的servlet对象

       ApplicationContextac = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());

       PrivilegeServiceprivilegeService = (PrivilegeService) ac.getBean("privilegeService");

       List<Privilege>  topPrivilegeList =privilegeService.findTopList();

       arg0.getServletContext().setAttribute("topPrivilegeList",topPrivilegeList);

 

}

 

 

接口:

public interfaceDaoSupport<T> {

    void save(T entity);

    void delete(Long id);

    void update(T entity);

    TgetById(Long id);

    List<T>getByIds(Long[] ids);

    List<T>findAll();

}

 

实现类

@Transactional

@SuppressWarnings("unchecked")

public classDaoSupportImpl<T> implements DaoSupport<T>{

    @Resource private SessionFactory sessionFactory;

    private Class<T> classz=null;

   

    public DaoSupportImpl(){

       //  使用反射技术得到T的真实类型

       ParameterizedTypept = (ParameterizedType) this.getClass().getGenericSuperclass();  //获取当前new的对象的泛型的父类类型

       this.classz = (Class<T>)pt.getActualTypeArguments()[0]; // 获取第一个类型参数<>中的参数类型

       //System.out.println(classz);

    }

   

    /**

     * 获取当前可用的session对象,这样子类也就可以用这个session

     * @return

     */

    private Session getSession(){

       return sessionFactory.getCurrentSession();

    }

   

    public void save(T entity) {

       getSession().save(entity);

    }

 

    public void delete(Long id) {

       Objectobj = getById(id);

       if (obj != null)

           getSession().delete(obj);

    }

 

    public void update(T entity) {

       getSession().update(entity);

    }

 

    public T getById(Long id) {

       return (T)getSession().get(classz, id);

    }

 

    public List<T>getByIds(Long[] ids) {

       if (ids == null || ids.length == 0){

           return Collections.EMPTY_LIST//  返回

       }else{

           returngetSession().createQuery(//

                  "From "+classz.getSimpleName()+" WHERE id IN (:ids)")//

                  .setParameterList("ids", ids)//

                  .list();

       }

    }

 

    public List<T> findAll(){

       returngetSession().createQuery("FROM "+classz.getSimpleName()).list();

    }

}

 

 

Service:

@Repository

public interfaceUserService extends DaoSupport<User> {

    //根据用户名和密码查询用户

    UserfindByLoginNameAndPassword(String loginName, String md5Hex);

 

}

 

ServiceImpl:

@Transactional

@Service("userService")

public classUserServiceImpl extends DaoSupportImpl<User> implements UserService {

    @Resource

    private SessionFactory sessionFactory;

   

    public UserfindByLoginNameAndPassword(String loginName, String md5Hex) {

      

       return (User) sessionFactory.getCurrentSession().createQuery(//

              "FROM User u WHERE u.loginName=? ANDu.password=?")//

              .setParameter(0,loginName)//

              .setParameter(1,md5Hex)//

              .uniqueResult();

    }

   

}

 

Action

 

public classBaseAction extends ActionSupport {

    @Resource(name="userService")protectedUserService userService;

}

 

 

@Controller

@Scope("prototype")

public classUserAction extends BaseAction {

    private User user;

    private Long departmantId;

    private Long[] roleIds;

    private Long id;

    //get,set

 

    //  删除

    public String delete(){

       userService.delete(id);

       return "toList";

    }  

}

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值