SSH框架项目学习记录

来源:互联网 发布:cnc编程学习 编辑:程序博客网 时间:2024/06/09 04:22

自从在培训机构使用过SSH框架以后,就很少接触了。一年以后再次使用有着不同的感受。发现以前学习到的东西好多就已经忘记了。觉得应该写点什么,正所谓好脑子不如烂笔头嘛。

首先先从struts2开始。

使用struts就不得不说一下s标签了。

使用s便签首先应该导入struts2便签库<%@taglib prefix="s" uri="/struts-tags" %> 最常用的导入方式。

struts2便签有许多,这里就先记录几个比较常用的标签。

<s:property> 标签: value属性显示放入的之(注:只能显示从后台传入前台的值而不是手动输入的值) 。这个标签也可以与html标签一起使用   例:<input name="partner.Found_year" id="found_year" size="6" maxlength="4" value="<s:property value="partner.Found_year"/>

<s:iterator>标签:遍历从后台传入的集合。例子

<s:iterator id="country" var="country" value="#session.countryList" status="count">
                    <s:if test="#count.index==0"><option value=""></option></s:if>
                <s:if test="partner.country==#count.index+1">
                <option value="${country.id}" selected="selected"><s:property value="#country.name"/>  </option>
                </s:if>
                <s:else>
                <option value="${country.id}"><s:property  value="#country.name"/>  </option>
                </s:else>
                </s:iterator>

例子中的value值就是从后台传入的需要遍历的集合,var用去遍历后的每一个数值的存放。sratus遍历的次数。这里在说明一下:<s:iterator>标签中还存在begin与end属性,用去记录循环开始的位置与结束的位置。

<s:if>与<s:else>标签:这两个标签主要用于页面上的判断通过上面的例子能看出这两个标签的用法。说明一下test属性里面写入的是判断条件。

<s:date>标签:这个标签主要用于页面上时间的显示问题 例:

<s:date name="companyId.createTime" format="yyyy-MM-dd HH:mm:ss.SSS"/>

其中的name属性放入的是需要显示的时间的值 fromat是需要显示的时间的格式。

<s:radio>标签:用于页面显示单选按钮例:

<s:radio name="companyHistory.publicFlag" id="public_flag" list="%{#{'1':'非公開','2':'公開'} }" value="1"/>

其中的list放入的是需要显示的单选按钮的键值对,其中的1,2 是键 非公开与公开是值。

value属性是默认值的显示。

以上算是比较常用的struts2标签。

总结一下:其中大部分的共性,如果有value属性的话,value就是需要显示的值而name就是需要上穿给的对象。

如果没value的话,那么name属性即使需要显示的值也是需要上传的对象。当然也有违反的比如s:radio的value是默认值。

(注:html标签的name也可上传与struts2标签的使用方法一致)

以下是关于标签的一些补充随时添加:

1.文章展示的时候,文章内容由于采用的富文本编辑器,所以里面是带有HTML标签的,这时直接用标签进行输出,例如:<s:property value="Obj.content" />

HTML标签会原样输出,因为struts标签会对html进行自动的编码,并且此标签有内置属性escape。此属性默认值是true,就是它控制着是否自动编码,所以加入escape="false"就OK了

例如<s:property value="Obj.content" escape="false"/>

2.关于前台调用后台静态方法:

页面显示一个属性nickName需要进行编码。

1。编写一个静态的公共方法。

package com.util;public static String encoder(String source,String charset){         return source ;}

2。在jsp页面中使用
<s:property value="@com.util.StringUtil@encoder(nickName,'UTF-8')"/>


3。在struts.xml中配置全局的
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>

关于后台:

传递和接收参数的方式:

我接触的主要有二种形式

第一种:通过get与set方法取得需要在后台定义变量并且进行get与set方法只要前台的跟后台使用同一个变量即可。

第二种:是通过request或者是session 后太通过setAttribute(a,b)方法把需要的值放入其中的a放入的是键 放入的是值。

前台取得的时候需要在键的前面加上#才能取得。

再就是struts2标签的配置文件问题简单的贴一个例子:

<?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="partner" extends="struts-default">
        <action name="Partner">
            <result type="chain">PartnerUpdate</result>
            <result name="system_error">/system_error.jsp</result>
        </action>
        
        <action name="PartnerUpdate" class="org.northsea.action.PartnerUpdateAction"
            method="doPartnerUpdateAction">
            <result name="true" type="chain">PartnerDetail</result>
            <result name="system_error">/system_error.jsp</result>
        </action>

</struts>

其中的<action>name就是from表单中action的名字。class是跳入的action的路径。而method是需要进入的方法名。 

<result>中的name是action中返回值的内容。里面写入的是需要跳转的页面type="chain"的意思是指此处是需要跳转到配置文件中的领一个action 其中放入的是action的name值。


关于struts2的上传与下载。

首先还是先贴一个例子

    private File upload;
    private String uploadFileName;

…………

    File work_path = new File(pathName + pathAdd);
            if(!work_path.exists()){
                work_path.mkdirs();
            }
            
            String fileName = this.getUploadFileName().toLowerCase();
            fileName = pathAdd + '/' + id + fileName.substring(fileName.lastIndexOf("."));

            if("".equals(fileName)){
                String tmpName = pathName + fileName;
                File file = new File(tmpName);
                if(file.exists()) file.delete();
            }
            InputStream in =new FileInputStream(this.getUpload());
            //InputStream in = uploadFile.getInputStream();
            byte[] bytes = new byte[in.available()];
            in.read(bytes);
    
            RandomAccessFile out = new RandomAccessFile(Const.getConfigProperty("UPLOAD_FOLDER") + fileName,"rw");
            out.write(bytes);

            in.close();
            out.close();

其中需要注意的是private File upload 就是前台页面上传递的文件。

而uploadFileName就是文件的名字。不需要在前台页面使用。struts2自带的  *FileName的值就是 *文件的文件名。

文件下载的例子:

public InputStream getDownLoadFile() throws IOException {
        try {
            InputStream inputStream=new FileInputStream(filePath + this.getFilename());        
            return inputStream;
        } catch (Exception e) {
            HttpServletResponse response=ServletActionContext.getResponse();
            response.sendRedirect("fileNotFound.jsp");
            e.printStackTrace();
            return null;
        }

…………

CompanyFile companyFile = fileDownloadService.findFileWay(id);    
             String[] strings=companyFile.getSaveName().split("/");
                for (int i = 0; i < strings.length; i++) {
                    if(strings[i].contains(".")){
                        this.setFilename(strings[i]);    
                    }
                }
            return "success";

下面是下载时xml的配置文件。

<action name="FileDownload" class="org.northsea.action.FileDownloadAction"
            method="doFileDownloadAction">
            <result name="success" type="stream">
                <param name="contentType">application/msword,application/vnd.ms-excel</param>
                <param name="contentDisposition">attachment;filename="${fileName}"</param>
                <param name="bufferSize">4096</param>  
                <param name="inputName">downLoadFile</param>
            </result>
            <result name="session_error">/session_error.jsp</result>
            <result name="kong">/partner/kong.jsp</result>
        </action>

以上是本次项目个人对于struts2的一些理解。


下面再来总结一下hibernate对入数据库的一些简单应用把。

关于hibernate它提倡一种面向对象的数据库操作。所以在建立model对象的时候他需要给model对象配置一个xml文件。用来关联数据库中的字段。具体的关联方法我就简单的贴一个列子吧。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2012/12/28 14:29:05 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="org.northsea.model.Bonus" table="bonus" schema="public">
        <id name="id" type="int">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="employeeId" type="string">
            <column name="employee_id" length="10" not-null="true" />
        </property>
        <property name="explanation" type="string">
            <column name="explanation" length="300" />
        </property>
        <property name="appliedYm" type="string">
            <column name="applied_ym" length="6" not-null="true" />
        </property>
        <property name="amount" type="int">
            <column name="amount" not-null="true" />
        </property>
        <property name="unemploymentInsurance" type="java.lang.Integer">
            <column name="unemployment_insurance" />
        </property>
        <property name="healthInsurance1" type="java.lang.Integer">
            <column name="health_insurance1" />
        </property>
        <property name="healthInsurance2" type="java.lang.Integer">
            <column name="health_insurance2" />
        </property>
        <property name="welfarePension" type="java.lang.Integer">
            <column name="welfare_pension" />
        </property>
        <property name="incomeTax" type="java.lang.Integer">
            <column name="income_tax" />
        </property>
        <property name="residenceTax" type="java.lang.Integer">
            <column name="residence_tax" />
        </property>
        <property name="deductionAmount" type="java.lang.Integer">
            <column name="deduction_amount" />
        </property>
        <property name="transferAmount" type="int">
            <column name="transfer_amount" not-null="true" />
        </property>
        <property name="createBy" type="string">
            <column name="create_by" length="15" not-null="true" />
        </property>
        <property name="createTime" type="timestamp">
            <column name="create_time" length="29" not-null="true" />
        </property>
        <property name="updateBy" type="string">
            <column name="update_by" length="15" />
        </property>
        <property name="updateTime" type="timestamp">
            <column name="update_time" length="29" />
        </property>
        <property name="payFlag" type="char">
            <column name="pay_flag" length="1" not-null="true" />
        </property>
        <property name="payBy" type="string">
            <column name="pay_by" length="15" />
        </property>
        <property name="payDate" type="date">
            <column name="pay_date" length="13" />
        </property>
        <property name="lockFlag" type="char">
            <column name="lock_flag" length="1" not-null="true" />
        </property>
        <property name="lockBy" type="string">
            <column name="lock_by" length="15" />
        </property>
        <property name="lockTime" type="timestamp">
            <column name="lock_time" length="29" />
        </property>
    </class>
</hibernate-mapping>
以上是关于对model对象的配置。

下面来介绍一下hiernate对于dao层也就是数据库的一些操作。

首先要继承HibernateDaoSupport才能使用hiernate的方法

对于操作数据库的语言分两种,一种是HQL就是hiernate推荐的面向对象操作数据库的语言。简单来一个例子

String HQL = "SELECT name,partnerId FROM PartnerCharger  WHERE id = "+id;
            List list =session.createQuery(HQL).list();

其中小写的部分都是对面里面的属性,而PartnerCharger 就是对象。从这个HQL就能看出它是以对象与对象的属性来操作数据库的。

执行HQL的方法之一,也就是执行完整的HQL的方法就是createQuery他是hibernate.session里面的方法。需要先定义session。

Session session = getSessionFactory().openSession();

还有一部分封装的方法为了使简单的HQL更加方便可以使用

final String HQL = "FROM Province WHERE COUNTRY = '" + homeland + "' ORDER BY ID";    
        
        ArrayList<Province> provinceList = (ArrayList<Province>) this.getHibernateTemplate().find(HQL);

这种方法的好处是可以直接返回对象。但是缺点就是局限性比较大。不适合复杂的HQL

下面来介绍一下SQL在hibernate中的使用方法。

String    sqlStr = "SELECT FOUND_DAY FROM COMPANY";
    Session session = getSessionFactory().openSession();
    List iterator = session.createSQLQuery(sqlStr).list();   
向上一面的例子就是典型的hiernate执行SQL的方法。

还有就是需要特别注意的地方就是character(n)这种数据类型在hiernate中只会截取第一个字符所以需要在SQL中加上cast(A.country as varchar(n))来进行一部转换。