ssh基本搭建,利用spring注解开发

本文详细介绍了如何搭建SSH(Spring+Struts+Hibernate)框架环境,并通过具体示例展示了Spring注解的使用方法,包括配置文件设置、类注解及属性注入等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下内容包括简单的ssh环境搭建和spring注解的简单使用。

把下面的配置文件复制过去改改内容就可以用了。


首先导入ssh所需的包


第一步、配置beans.xml  (*)

spring+hibernate,beans.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: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-2.5.xsd

          http://www.springframework.org/schema/context

          http://www.springframework.org/schema/context/spring-context-2.5.xsd

          http://www.springframework.org/schema/aop

          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

          http://www.springframework.org/schema/tx

          http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:component-scan base-package="pers"/>

    <aop:aspectj-autoproxy/>    

   

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

        <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>

        <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8"/>

        <property name="username" value="root"/>

        <property name="password" value=""/>

         <!-- 连接池启动时的初始值 -->

        <property name="initialSize" value="1"/>

        <!-- 连接池的最大值 -->

        <property name="maxActive" value="500"/>

        <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

        <property name="maxIdle" value="2"/>

        <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

        <property name="minIdle" value="1"/>

      </bean>

   

   

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

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

        <property name="mappingResources">

           <list>

             <value>pers/po/Clazz.hbm.xml</value>

             <value>pers/po/Student.hbm.xml</value>

           </list>

        </property>

         <property name="hibernateProperties">

           <value>

           <!-- 方言 -->

              hibernate.dialect=org.hibernate.dialect.MySQLDialect

               <!-- SessionFactory创建时,自动检查数据库结构,或者将数据库schemaDDL导出到数据库. 使用 create-drop,在显式关闭SessionFactory时,将drop掉数据库schema. 取值 validate | update | create | create-drop -->

               hibernate.hbm2ddl.auto=update

               <!-- 输出所有SQL语句到控制台. 有一个另外的选择是把org.hibernate.SQL这个log category设为debug eg. true | false -->

              hibernate.show_sql=false

               <!-- logconsole中打印出更漂亮的SQL取值 true |false -->

              hibernate.format_sql=false

               <!-- 能用来完全禁止使用二级缓存. 对那些在类的映射定义中指定<cache>的类,会默认开启二级缓存. 取值 true|false -->

              hibernate.cache.use_second_level_cache=true

               <!--允许查询缓存, 个别查询仍然需要被设置为可缓存的取值true|false  -->

               hibernate.cache.use_query_cache=false

             </value>

         </property>

    </bean>

   

    <!-- 事务管理 -->

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

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

    </bean>

    <!-- 事物注解支持 -->

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

 

</beans>

 

Beans.xml中有这几个需要修改的地方

1、

<context:component-scan base-package="pers"/>

这是一个spring注解的扫描器,在xml配置了这个标签后,spring可以自动去扫描pers下面或者子包下面的java文件,如果扫描到有@Component@Controller@Service等这些注解的类,则把这些类注册为bean

 

2、

<property name="url"value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8"/>

        <property name="username" value="root"/>

        <property name="password" value=""/>

这里是数据库配置, url是数据库路径,Username是用户名,Password是密码。  我这个配置的是mysql

 

3、

     <property name="mappingResources">

           <list>

             <value>pers/po/Clazz.hbm.xml</value>

             <value>pers/po/Student.hbm.xml</value>

           </list>

        </property>

 

spring加载hibernate映射文件。Value值需要改成自己的映射文件路径

 

 

 

 

 

第二步、配置struts.xml

<?xml version="1.0"encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

       "-//Apache Software Foundation//DTD StrutsConfiguration 2.0//EN"

       "http://struts.apache.org/dtds/struts-2.0.dtd">

 

<struts>

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

       <action name="stu"class="stuaction" method="show">

              <result name="list">/index.jsp</result>

           </action>

    </package>

</struts>

简单的标签、属性介绍:

"<package>"中 

           name:包名,要唯一,自己随便定义

           namespace:虚拟路径

           extends:每个包都应该继承struts-default包,因为struts2很多核心功能都是拦截器来实现。

"<action>中"

           name:名字,路径的一部分,自己随便定义

           class:处理类

           method:用哪个方法处理

"<result>":视图

action的class可以写自己配制的actionbean名称,也可以写相对路径(如:cn.itcast.action.HelloWorldAction)。

 

第三步、配置web.xml

<?xml version="1.0"encoding="UTF-8"?>

<web-app version="2.4"

    xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

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

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

   

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list> 

</web-app>

 

没有特别需要修改的地方,注意一下:

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

这个要写src下配置文件的名字,如果修改了文件名,这里记得改

 

第四步、给类加注解

 

简单介绍,bean注解分为这么几个:

@Service用于标注业务层组件、@Controller用于标注控制层组件(如struts中action)、

@Repository用于标注数据访问组件、即DAO组件。而@Component泛指组件,当组件不好归类的时候

这几个注解作用其实是一样,都是把这些类注册为bean,只是名字不一样。比如你全用@Service也ok,但不推荐这么做

 

1、首先给dao、action、service分别加上注解

Dao:

 

@Repository("studao") @Transactional

public class StudentDaoImpl {

 

    @Resource

    SessionFactory sessionFactory;

 

    public boolean add(Student stu)

    {

       try{

           sessionFactory.getCurrentSession().save(stu);

           return true;

       }catch (Exception e) {

           // TODO: handleexception

           return false;

       }

    }

    public List<Student> list()

    {

      

       String hql = "fromStudent";

       Query query = sessionFactory.getCurrentSession().createQuery(hql);

       return query.list();

    //  returnsessionFactory.getCurrentSession().createQuery("fromStudent").list();

    }

    public boolean remove(Student stu)

    {

      

       Session session = sessionFactory.getCurrentSession();

       session.delete(stu);

       return true;

    }

    public Student getStuById(int id)

    {

       String hql = "fromStudent stu where stu.id=:id";

       Query query = sessionFactory.getCurrentSession().createQuery(hql);

       query.setInteger("id",id);

       return (Student)query.uniqueResult();

    }

}

简单说明:

 

1、@Repository("studao"):  括号中是我们给这个bean起的名字,以便我们操作。

 

2、DAO比其他的组件多一个‘@Transactional’在执行方法时自动处理一些事物功能,比如开启事物和提交事务,必写。

 

3、@Resource

SessionFactory sessionFactory;

@Resource用于获取bean,是先name匹配,如果没有,自动type匹配。

例子:根据name匹配:

@Resource(name=“beanName”)

这里没有制定name,自动进行了type匹配。获取的是我们在beans.xml中配置的sessionFactory

 基于sessionFactory的基本的增删查改操作已经写出。

 

 

Service:

@Service("stuservice")

public class StudentServiceImpl {

 

    @Resource

    StudentDaoImpl studao;

   

    public boolean add(Student stu)

    {

       return studao.add(stu);

    }

    public List<Student> getlist()

    {

       return studao.list();

    }

    public boolean remove(Student stu)

    {

       return studao.remove(stu);

    }

    public Student getStuById(int id)

    {

       return studao.getStuById(id);

    }

}

简单说明:

之前说过@Resource的作用,比如这里需要获取前面的StudentDaoImpl,其实也可以使用name获取:@Resource(name=”studao”)。

studao是我们刚才配置的StudentDaoImpl的bean名

 

Action:

 

@Controller("stuaction")

public class StudentAction {

 

    @Resource(name="stuservice")

    StudentServiceImpl stuservice;

   

    private Student stu;

    public Student getStu() {

       return stu;

    }

    public void setStu(Student stu) {

       this.stu = stu;

    }  

     public String show()

    {

       //获取所有的学生列表集合,并存到session

    ServletActionContext.getRequest().getSession().setAttribute("list",stuservice.getlist());

       return "list";

    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值