Struts2+Spring2.5+ibatis+ExtJS3.1 基于注解框架搭建

24 篇文章 0 订阅
8 篇文章 0 订阅
1、引入相应的包:查看以下图片


2、
jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=admin

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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd" >

<context:annotation-config />
<!-- 根据base-package指定的路径,扫描其下所有包含注解的Bean,并自动注入 -->
<context:component-scan base-package="com.huawei.boss"/>

<!-- 启用aspectj -->  
    <!-- <aop:aspectj-autoproxy />   -->
   
<!-- 自动加载 jdbc.properties -->
<bean id="globalConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<!-- 配置hibernate
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
-->
<!-- 根据value中定义的路径来扫描其下所有的注解实体类 -->

<!--
<property name="packagesToScan" value="com.huawei.boss.entity.*"></property>
</bean>
-->

<!-- 读取ibatis配置文件 -->
     <bean id="sqlMapClient"  class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
     <property name="dataSource" ref="dataSource" />
<property name="configLocation">
   <value>classpath:SqlMapConfig.xml</value>
</property>
</bean>

<!-- 使用Spring的Template 进行数据库管理 -->

<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
        <property name="sqlMapClient" ref="sqlMapClient" />
    </bean>

    <!-- 提供对SqlMapClientTemplate的封装 -->
     <!--
    <bean id="sqlMapClientTemplateManager" class="com.huawei.boss.common.dao.SqlMapClientTemplateManagerImpl">
    <property name="sqlMapClientTemplate" ref="sqlMapClientTemplate" />
    </bean>
     -->


<!-- 配置事务定义 ibatis -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 注解方式定义事务(@Transactional),proxy-target-class="true"表示采用动态代理类来管理事务,如果是false表示采用接口代理来管理事务(默认值为false) -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

<!-- 采用jta事务管理
<bean id="jotm" class="org.springframework.transaction.jta.JotmFactoryBean"/>
<bean id="jtaTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
     <property name="userTransaction">
     <ref local="jotm"/>
     </property>
</bean>
<tx:annotation-driven transaction-manager="jtaTransactionManager"  proxy-target-class="true" />
-->
</beans>
-----------------(2)-----------------------------

1、创建ibatis配置文件
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMapConfig     
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"     
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="true" />

  <!-- 可以添加多个 -->    
  <sqlMap resource="com/****/entity/StafferInfoBean.xml"/>
 
</sqlMapConfig>
2、struts.xml

<?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>
<!-- 否支持动态方法调用 -->
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="true" />
<!-- 将struts的action交由spring管理  不在由struts的工厂介入 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 支持.do的后缀 -->
<constant name="struts.action.extension" value="action,do" />
<!-- 指定Web应用的默认编码集 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- Web应用的默认Locale -->
<constant name="struts.locale" value="zh-CN" />


<!-- 引入所有的struts xml -->
<include file="login.xml"></include>


</struts>

3、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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  <!-- 读取spring -->
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 
  <!-- 防止内存泄露,更好的处理内存 -->
  <listener>
  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
 
  <!-- Spring 编码过滤器 -->
  <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
  <param-name>encoding</param-name>
  <param-value>GBK</param-value>
  </init-param>
  <init-param>
  <param-name>forceEncoding</param-name>
  <param-value>true</param-value>
  </init-param>
  </filter>
  <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</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>
</web-app>

---------------------------(3)---------------------------------

1、创建login.xml

<?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="login" extends="struts-default">
       
       
        <action name="initLogin">
        <result name="success">/WEB-INF/portal/portal.jsp</result>
        </action>
        <!-- 转向添加页面 -->
        <action name="loginAction" class="loginAction" method="login">
        <result name="success">/WEB-INF/portal/portal.jsp</result>
        </action>

</package>

</struts>
2、建立LoginAction.java
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;




@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends BaseAction
{

    /**
     * 注释内容
     */
    private static final long serialVersionUID = 9146562136905868429L;
   
    @Resource LoginService loginServiceImpl;
   
    /**
     * 登录验证
     * <功能详细描述>
     * @return
     * @see [类、类#方法、类#成员]
     */
    public String login()
    {
        HttpServletRequest request = getRequest();
    String staffId = request.getParameter("staffId");
    String staffPwd = request.getParameter("staffPwd");
    boolean flag = loginServiceImpl.loginService(staffId, staffPwd);
    String returnMsg = "{failure:false}";
        if (flag)
        {
            // returnMsg = "{success:true}";
            return SUCCESS;
        }
        else
        {
            returnMsg = "{failure:false}";
            outJsonString(returnMsg);
            return null;
        }
    }
   
}

3、创建Server接口和实现类
LoginService.java

public interface LoginService
{
    public boolean loginService(String staffId, String password);
}

LoginServiceImpl.java


import javax.annotation.Resource;

import org.springframework.stereotype.Service;
@Service("loginServiceImpl")
public class LoginServiceImpl extends BaseService implements LoginService
{
    @Resource LoginDao loginDaoImpl;

    public boolean loginService(String staffId, String password)
    {
        StafferInfoBean stafferInfoBean = new StafferInfoBean();
        stafferInfoBean.setStaffId(staffId);
        stafferInfoBean.setStaffPwd(password);
       
        StafferInfoBean stafferInfo = loginDaoImpl.loginDao(stafferInfoBean);
        if (stafferInfo != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
----------------------(4)----------------------------------------

1、创建实体类StafferInfoBean.xml  StafferInfoBean.java

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

<!DOCTYPE sqlMap     
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"     
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="common">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="stafferInfoBean" type="com.huawei.boss.entity.StafferInfoBean"/>
   
      
  <select id="getCurrFormatDate" parameterClass="java.lang.String" resultClass="java.lang.String">
   <![CDATA[
select to_char(sysdate,#dateFormat#) from dual
]]>
  </select>

  <!-- 登录获取用户 -->
  <select id="getLoginUser" parameterClass="stafferInfoBean" resultClass="stafferInfoBean">
   <![CDATA[
select staffId, staffPwd from staffer where staffid = #staffId# and staffpwd = #staffPwd#
]]>
  </select>
</sqlMap>



@Entity
public class StafferInfoBean implements Serializable
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = -2749598508449992482L;

    private String staffId;
   
    private String staffPwd;
   
    public StafferInfoBean()
    {
       
    }
   
    public String getStaffId()
    {
        return staffId;
    }
   
    public void setStaffId(String staffId)
    {
        this.staffId = staffId;
    }
   
    public String getStaffPwd()
    {
        return staffPwd;
    }
   
    public void setStaffPwd(String staffPwd)
    {
        this.staffPwd = staffPwd;
    }
   
}


2、创建Dao
LoginDao.java

public interface LoginDao
{
    public StafferInfoBean loginDao(StafferInfoBean stafferInfoBean);
}

LoginDaoImpl.java

import javax.annotation.Resource;

import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.stereotype.Repository;
@Repository("loginDaoImpl")
public class LoginDaoImpl implements LoginDao
{
   
    @Resource SqlMapClientTemplate sqlMapClientTemplate;
   
    /**
     * @param stafferInfoBean
     * @return
     */
    @Override
    public StafferInfoBean loginDao(StafferInfoBean stafferInfoBean)
    {
        StafferInfoBean stafferInfo = null;
        try
        {
            stafferInfo = (StafferInfoBean)sqlMapClientTemplate
                    .queryForObject("common.getLoginUser", stafferInfoBean);
           
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return stafferInfo;
    }
   
}

3、迟来的BaseAction
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
* 所有Action的基类
*
* @author
* @version [版本号, Mar 7, 2010]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class BaseAction extends ActionSupport
{
   
    /**
     * 序列号
     */
    private static final long serialVersionUID = 1L;
   
    /**
     * 取得HttpServletRequest对象 <功能详细描述>
     *
     * @return
     * @see [类、类#方法、类#成员]
     */
    public HttpServletRequest getRequest()
    {
        return ServletActionContext.getRequest();
    }
   
    /**
     * 取得HttpServletRequest对象 <功能详细描述>
     *
     * @return
     * @see [类、类#方法、类#成员]
     */
    public HttpServletResponse getResponse()
    {
        return ServletActionContext.getResponse();
    }
   
    /**
     * 取得HttpSession对象 <功能详细描述>
     *
     * @return
     * @see [类、类#方法、类#成员]
     */
    public HttpSession getSession()
    {
        return ServletActionContext.getRequest().getSession();
    }
   
    /**
     * 返回日志对象
     *
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected Logger getLog()
    {
        return Logger.getLogger(BaseAction.class);
    }
   
    /**
     * 取得参数 <功能详细描述>
     *
     * @param name
     * @return
     * @see [类、类#方法、类#成员]
     */
    public String getParameter(String name)
    {
        return ServletActionContext.getRequest().getParameter(name);
    }
   
    /**
     * 设置 request 的属性.
     *
     * @param name 属性名
     * @param value 属性值
     */
    public void setAttribute(String name, Object value)
    {
        ServletActionContext.getRequest().setAttribute(name, value);
    }
   
    /**
     * 获取 request 的属性.
     *
     * @param name 属性名
     */
    public Object getAttribute(String name)
    {
        return ServletActionContext.getRequest().getAttribute(name);
    }
   
    /**
     * 读取 session 中的属性值
     *
     * @param name
     * @return
     */
    @SuppressWarnings("unchecked")
    public Object getSessionAttribute(String key)
    {
        ActionContext ctx = ActionContext.getContext();
        Map session = ctx.getSession();
        return session.get(key);
    }
   
    /**
     * 向 session 设置属性值
     *
     * @param name
     * @param value
     */
    @SuppressWarnings("unchecked")
    public void setSessionAttribute(Object key, Object value)
    {
        ActionContext ctx = ActionContext.getContext();
        Map session = ctx.getSession();
        session.put(key, value);
    }
   
    /**
     * 对返回值的封装
     * <功能详细描述>
     * @param str
     * @see [类、类#方法、类#成员]
     */
    public void outJsonString(String str)
    {
        getResponse().setContentType("text/javascript;charset=GBK");
        outString(str);
    }
   
    public void outJson(Object obj)
    {
        outJsonString(JSONObject.fromObject(obj).toString());
    }
   
    public void outJsonArray(Object array)
    {
        outJsonArray(JSONArray.fromObject(array).toString());
    }
   
    public void outString(String str)
    {
        try
        {
            PrintWriter out = getResponse().getWriter();
            out.write(str);
        }
        catch (IOException e)
        {
               
        }
    }
   
    public void outXMLString(String xmlStr)
    {
        getResponse().setContentType("application/xml;charset=GBK");
        outString(xmlStr); 
    }
}
----------------------------(5)---------------------------------------

1、BaseService
public class BaseService
{
    /**
     * 返回日志对象
     *
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected Logger getLog()
    {
        return Logger.getLogger(BaseAction.class);
    }
}

2、创建页面
login.jsp
<%@ page language="java"  pageEncoding="GBK"%>
<html>
<head>
    <title>Custom Layouts and Containers - Login Example</title>

    <!-- ** CSS ** -->
    <!-- base library -->
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/extjs3.1/resources/css/ext-all.css" />

    <!-- ** Javascript ** -->
    <!-- ExtJS library: base/adapter -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/extjs3.1/adapter/ext/ext-base.js"></script>

    <!-- ExtJS library: all widgets -->
    <!--
    <script type="text/javascript" src="${pageContext.request.contextPath}/extjs3.1/ext-all.js"></script>
     -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/extjs3.1/ext-all-debug.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/extjs3.1/ext-lang-zh_CN.js" charset="utf-8"></script>

<script type="text/javascript" src="${pageContext.request.contextPath}/js/login/login.js"></script>

</head>
<body>
<div id="loginPanel" align="center"></div>
</body>
</html>


login.js

/*!
* Ext JS Library 3.1.1
* Copyright(c) 2006-2010 Ext JS, LLC
* licensing@extjs.com
* http://www.extjs.com/license
*/
Ext.onReady(function() {
Ext.QuickTips.init();   //用于消息提示
    Ext.form.Field.prototype.msgTarget = 'side'; 
   
    var loginForm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        layout:'absolute',
        defaultType: 'textfield',

        items: [{
            x: 0,
            y: 5,
            xtype:'label',
            text: 'StaffNo:'
        },{
            x: 60,
            y: 0,
            name: 'staffId',
            anchor:'100%',  // anchor width by percentage
            allowBlank: false,  
            blankText: 'StaffNo is not null'
        },{
            x: 0,
            y: 35,
            xtype:'label',
            text: 'password:'
        },{
            x: 60,
            y: 30,
            name: 'staffPwd',
            inputType:'password',
            anchor: '100%',  // anchor width by percentage
            allowBlank: false,  
            blankText: 'staffPwd is not null'
        }]
    });

    var window = new Ext.Window({
        title: 'Login System',
        width: 300,
        height:150,
        layout: 'fit',
        plain:true,
        bodyStyle:'padding:5px;',
        buttonAlign:'center',
        items: loginForm,
   
        keys:{  
            key: 13,  
            fn:loginAction  
        },  
        buttons: [{
            text: 'Send',
            handler:loginAction
        },{
            text: 'Cancel',
            handler:function(){
                loginForm.form.reset();
            }
        }]
    });

    window.show();
   
    //登录Action
    function loginAction()
    {
       
        //可以增加校验
        loginForm.form.submit({
            waitMsg:'正在登录...', /* 表示提交过程中间的等待信息。 */ 
            url:'/NGFRAME/login/loginAction.action', /* 表示表单提交的时候的路径。 */  
            method:'post',
            success: onLoginSuccess, /* 服务器返回正确的信息之后我们调用的方法。 */  
            failure: onFailure /* 服务器返回错误的信息之后我们调用的方法。 */  
        });  
        return;
    }
   
    //登录成功
    function onLoginSuccess()
    {
        //Ext.Msg.alert('success', 'Changes saved successfully.');
    }
    //登录失败
    function onFailure()
    {
        Ext.Msg.alert('failure', '登录失败!,用户名或密码错误');
    }
});

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值