ssh框架初步搭载

1.导入jar包
2.创建web.xml文件,配置spring监听器和struts2的过滤器

<!-- Spring框架使用监听器,服务器启动的时候加载Spring的配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 监听器默认加载WEB-INF/application.xml -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
<!-- 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>

3.配置db.properties文件加载数据库的基本配置

jdbcUrl=jdbc:mysql://localhost:3306/myshop?useUnicode=true&characterEncoding=utf8
driverClass=com.mysql.jdbc.Driver
user=root
password=root
initialPoolSize=10
maxPoolSize=30

4.applicationContext的配置
(一)

 <!-- 导入外部的properties配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

(二)

<!-- 配置c3p0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="driverClass" value="${driverClass}"></property>
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
        <property name="initialPoolSize" value="${initialPoolSize}"></property>
        <!--连接池中保留的最小连接数。Default: 3 -->
        <property name="minPoolSize" value="3"></property>
        <!--连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize" value="${maxPoolSize}"></property>
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement" value="3"></property>
        <!--最大空闲时间,1800秒内未使用则连接被丢弃,若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime" value="1800"></property>
    </bean>

(三)sessionFactory的配置

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!--配置数据库属性 -->
        <property name="dataSource" ref="dataSource"></property>
        <!--配置hibernate属性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="javax.persistence.validation.mode">none</prop>
            </props>
        </property>
        <property name="mappingLocations">
            <list>
                <value>classpath:cn/itcast/shop/*/entity/*.hbm.xml</value> 
            </list>
        </property>
    </bean>

(四) 事务的配置
两种方式:

<!-- 事务管理 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

<!-- 事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="list*" read-only="true"/>
            <tx:method name="*" rollback-for="Throwable"/>
        </tx:attributes>
    </tx:advice>
<!-- aop配置被事务控制的类 -->
    <aop:config>
        <aop:pointcut id="serviceOperation" expression="bean(*Service)"/> <!-- 扫描以Service结尾的bean -->
<!-- <aop:pointcut id="serviceOperation" expression="execution(* cn.itcast..service.impl.*.*(..))"/>  --><!--处理事务的类具体落实到service路径的配置 -- >
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
    </aop:config>

②在service类前加上@Transactional,声明这个service所有方法需要事务管理。每一个业务方法开始时都会打开一个事务。

<!-- 声明式事务管理 -->
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <!-- 注入 sessionFactory-->
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

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

(五)创建bean

<bean id="baseDao" abstract="true">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
<!-- 引入外部sprign配置文件 -->
    <import resource="classpath:cn/itcast/shop/*/conf/*-spring.xml"/>

5.创建项目中总struts2配置文件

<!-- 禁用动态方法访问 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <!-- 配置成开发模式 -->
    <constant name="struts.devMode" value="true" />
    <!-- 配置拓展名为action -->
    <constant name="struts.action.extention" value="action" />
    <!-- 把主题配置成simple -->
    <constant name="struts.ui.theme" value="simple" />

再次将子配置文件添加进来

<!-- 包含struts配置文件 -->
    <include file="cn/itcast/shop/index/conf/index-struts.xml"></include>

6.创建实体类entity包下的user类

public class User implements Serializable{

    private Integer uid ;
    private String username;
    private String password;
    private String name;
    private String email;
    private String phone;
    private String addr;
    private String sex;

    public Integer getUid() {
        return uid;
    }
    public void setUid(Integer uid) {
        this.uid = uid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getAddr() {
        return addr;
    }
    public void setAddr(String addr) {
        this.addr = addr;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }


}

7.创建entity下的User.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>
    <class name="cn.itcast.shop.user.entity.User" table="user">
        <!-- 配置唯一标识 -->
        <id name="uid" column="uid">
            <generator class="native"/>
        </id>
        <!-- 配置普通属性 -->
        <property name="username" column="username"/>
        <property name="password" column="password"/>
        <property name="name" column="name"/>
        <property name="email" column="email"/>
        <property name="phone" column="phone"/>
        <property name="addr" column="addr"/>
        <property name="sex" column="sex"/>
    </class>
</hibernate-mapping>

8.抽取以BaseDao和BaseService为名的核心代码

①BaseDao

public interface BaseDao<T> {

    //新增
    public void save(T entity);

    //更新
    public void update(T entity);

    //根据id删除
    public void deleteById(Serializable id);

    //根据id查找
    public T findObjectById(Serializable id);

    //查找列表
    public List<T> findObjects();

}

②BaseDaoImpl

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

    Class<T> clazz;

    public BaseDaoImpl(){
        ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
        clazz = (Class<T>)pt.getActualTypeArguments()[0];
    }

    @Override
    public void save(T entity) {
        // TODO Auto-generated method stub
        getHibernateTemplate().save(entity);
    }

    @Override
    public void update(T entity) {
        // TODO Auto-generated method stub
        getHibernateTemplate().update(entity);
    }

    @Override
    public void deleteById(Serializable id) {
        // TODO Auto-generated method stub
        getHibernateTemplate().delete(findObjectById(id));
    }

    @Override
    public T findObjectById(Serializable id) {
        // TODO Auto-generated method stub
        return getHibernateTemplate().get(clazz, id);
    }

    @Override
    public List<T> findObjects() {
        // TODO Auto-generated method stub
        Query query = getSession().createQuery("FROM "+clazz.getSimpleName());
        return query.list();
    }

}

③BaseService

public interface BaseService<T> {


    //新增
    public void save(T entity);

    //更新
    public void update(T entity);

    //根据id删除
    public void deleteById(Serializable id);

    //根据id查找
    public T findObjectById(Serializable id);

    //查找列表
    public List<T> findObjects();
}

④BaseServiceImpl

public class BaseServiceImpl<T> implements BaseService<T> {

    private BaseDao<T> baseDao;

    public void setBaseDao(BaseDao<T> baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public void save(T entity) {
        // TODO Auto-generated method stub
        baseDao.save(entity);
    }

    @Override
    public void update(T entity) {
        // TODO Auto-generated method stub
        baseDao.update(entity);
    }

    @Override
    public void deleteById(Serializable id) {
        // TODO Auto-generated method stub
        baseDao.deleteById(id);
    }

    @Override
    public T findObjectById(Serializable id) {
        // TODO Auto-generated method stub
        return baseDao.findObjectById(id);
    }

    @Override
    public List<T> findObjects() {
        // TODO Auto-generated method stub
        return baseDao.findObjects();
    }

}

9.使用具体的业务代码继承上述的核心代码
①UserDao

public interface UserDao extends BaseDao<User> {

    public User findUserByAccountAndPassword(String username, String password);


}

②UserDaoImpl

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {


}

③UserService

public interface UserService extends BaseService<User>{

}

④UserSericeImpl

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    private UserDao userDao ;

    @Resource
    public void setUserDao(UserDao userDao) {
        super.setBaseDao(userDao);
        this.userDao = userDao;
    }
}

10.编写action代码

public class UserAction extends ActionSupport {


    @Resource
    private UserService userService ;

    private User user ; 

    //跳转到注册页面
    public String registerPage(){
        return "registerPageSuccess";
    }

    //实行注册功能
    public String register(){
        userService.save(user);
        return "registerSuccess";
    }

    //跳转到登陆页面
    public String loginPage(){
        return "loginPageSuccess";
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }


}

11.配置子配置文件user-struts和user-spring文件
①user-struts

<?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="user-action" namespace="/user" extends="struts-default">
        <action name="user_*" class="userAction" method="{1}">
            <result name="registerPageSuccess">/WEB-INF/jsp/user/register.jsp</result>
            <result name="registerSuccess">>/WEB-INF/jsp/index/success.jsp</result>         
        </action>
    </package>

</struts>

@user-spring文件

<?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-3.0.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="userAction" class="cn.itcast.shop.user.action.UserAction"></bean>

    <bean id="userDao" class="cn.itcast.shop.user.dao.impl.UserDaoImpl" parent="baseDao"></bean>

    <!-- 扫描service -->
    <context:component-scan base-package="cn.itcast.shop.user.service.impl"></context:component-scan>

</beans>

最最后———————————————-

配置文件的注解和xml配置的区分:
注解:

<!-- 扫描service -->
    <context:component-scan base-package="cn.itcast.shop.user.service.impl"></context:component-scan>

那么就无需在xml 文件中创建bean,只需在service类上注入就行

@Service("userService")
    public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    }

同时用@Resource进行属性的装配

@Resource
    private UserDao userDao ;

xml配置:

<!-- 配置Dao================================== -->
    <bean id="userDao" class="cn.itcast.shop.user.UserDao">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

<!-- 配置Service================================== -->
    <bean id="userService" class="cn.itcast.shop.user.UserService">
        <property name="userDao" ref="userDao"/>
    </bean>
<!-- 配置Action================================== -->
    <bean id="userAction" class="cn.itcast.shop.user.UserAction" scope="prototype">
        <property name="userService" ref="userService"/>
    </bean>

那么在实际代码中需

// 注入Dao
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值