Ajax+Struts2+Spring2+Hibernate3入门实例

开发环境eclipse+tomcat+mysql。

1 建一个web工程。在web.xml里加入struts2和spring的配置。

<?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>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

2 创建po。Commodit.java

public class Commodity {
    int id;
    String name;
    int amount;
    double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getAmount() {
        return amount;
    }

    public double getPrice() {
        return price;
    }
}

3 写hibernate的映射文件。Commodity.hbm.xml,和po放在同一目录。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="qw.po.Commodity" table="commodity">
        <id name="id">
            <generator class="increment"></generator>
        </id>
        <property name="name"></property>
        <property name="amount"></property>
        <property name="price"></property>
    </class>
</hibernate-mapping>

4 写个dao。CommodityDAO.java

public class CommodityDAO {
    HibernateTemplate ht;
    private SessionFactory sessionfactory;
    public void setHt() {
        if(ht==null){
            ht =new HibernateTemplate(sessionfactory);
        }
    }
    public void setSessionfactory(SessionFactory sessionfactory) {
        this.sessionfactory = sessionfactory;
    }
    @SuppressWarnings("unchecked")
    public List findAllCommodity() {
        setHt();
        return ht.find("from Commodity");//持久化类的类名
    }
}

5 写action,调用dao完成业务逻辑,其实这块应该分出service层的,但是简单例子就不弄那么复杂了。中间两个方法,service供页面提交表单调用,ajax供页面ajax请求调用。

public class Action extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String message;
    public CommodityDAO commoditydao;
   
    public List searchResult;
   
    public String execute() throws Exception {
        return SUCCESS;
    }

    public String search() throws Exception {
        System.out.println("查询开始");
        System.out.println("message:"+message);
        setSearchResult(commoditydao.findAllCommodity());
        return SUCCESS;
    }
    public String ajax() throws Exception {
        System.out.println("ajax请求");
        ActionContext ctx = ActionContext.getContext();     
        HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
        PrintWriter out=response.getWriter();
        out.println("hello world!");
        return null;
    }

    public List<Commodity> getSearchResult() {
        return searchResult;
    }

    public void setSearchResult(List<Commodity> searchResult) {
        this.searchResult = searchResult;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public CommodityDAO getCommoditydao() {
        return commoditydao;
    }

    public void setCommoditydao(CommodityDAO commoditydao) {
        this.commoditydao = commoditydao;
    }
   
}

6 下面就是struts.xml配置文件,放在src根目录下。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="qw.action" extends="struts-default">
        <action name="search" class="Action" method="search">
            <result>/HelloWorld.jsp</result>
        </action>
        <action name="ajax" class="Action" method="ajax">
        </action>
    </package>
</struts>

7 写spring的applicationContext.xml配置文件。放在web-inf下。

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

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/qw</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>aq1sw2de</value>
        </property>
    </bean>
   
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref local="dataSource" />
        </property>
        <property name="mappingResources">
            <list>
                <value>qw/po/Commodity.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
   
    <bean id="CommodityDAO" class="qw.dao.CommodityDAO">
        <property name="sessionfactory">
            <ref local="sessionFactory" />
        </property>
    </bean>

    <bean id="Action" class="qw.action.Action" scope="prototype">
        <property name="commoditydao">
            <ref local="CommodityDAO" />
        </property>
        <property name="message">
            <value>恭喜你传值成功!</value>
        </property>
    </bean>

</beans>

8 来个页面HelloWorld.jsp.

<%@ page language="java" pageEncoding="GB2312"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<html>
    <head>
        <title>Hello World!</title>
        <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
        <link href="./css/list.css" rel="stylesheet" type="text/css">

        <script src="./js/ext-core-debug.js"></script>
        <script type="text/javascript">
     var xmlHttp;
function callServer() {
    if(window.XMLHttpRequest){
          xmlHttp=new XMLHttpRequest();
    }else if(window.ActiveXObject){
          xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
    }
    var url="./qw/ajax";
      xmlHttp.open("GET", url, true);
      xmlHttp.onreadystatechange = updatePage;
      xmlHttp.send(null);
}

function updatePage() {
  if (xmlHttp.readyState == 4) {
    var response = xmlHttp.responseText;
     <!-- document.getElementById("ajaxreturnvalue").value = response+" qw";  -->
   Ext.getDom('ajaxreturnvalue').value = response;
    
  }
}
</script>
    </head>
    <body>
        <div>
            <input type="button" value="Ajax提交" οnclick="return callServer();">
            <p>
                Ajax返回值:
                <input type="text" id="ajaxreturnvalue" size="25" />
            </p>
        </div>
        <form action="./qw/search" method="post">
<div>
                <input type="submit" value="提交表单">
            </div>
            <div>
                <s:property value="message" />
            </div>
            <s:iterator value="searchResult">
                <div>
                    商品名:
                    <s:property value="name" />
                    数量:
                    <s:property value="amount" />
                    价格:
                    <s:property value="price" />
                </div>
            </s:iterator>
        </form>
    </body>
</html>

9 部署到tomcat上,开始ssh之旅!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值