我的最新日志

  • Request中getContextPath、request.getRealPath的区别

    2008-10-09

    假定你的web application 名称为news,你在浏览器中输入请求路径:

    http://localhost:8080/news/main/list.jsp

     

    则执行下面向行代码后打印出如下结果:

    1、 System.out.println(request.getContextPath());

    打印结果:/news
      2、System.out.println(request.getServletPath());

    打印结果:/main/list.jsp
     3、 System.out.println(request.getRequestURI());

    打印结果:/news/main/list.jsp
     4、 System.out.println(request.getRealPath("/"));

    打印结果:F:\Tomcat 6.0\webapps\news\test

    想不清楚的代码或原理,动手试验一般会找到答案!!!

    文章出处:http://www.diybl.com/course/1_web/webjs/2007923/73376.html

  • JS+DIV实现标签页

    2008-9-11

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>标签示例</title>
    <style type="text/css">
    body { font-size:14px; font-family:"宋体"}
    ol li { margin:8px}
    #con { font-size:12px; width:600px; margin:0 auto}
    #tags { height:23px; width:400px; margin:0; padding:0; margin-left:10px}
    #tags li { float:left; margin-right:1px; background:url(images/tagleft.gif) no-repeat left bottom; height:23px; list-style-type:none}
    #tags li a { text-decoration:none; float:left; background:url(images/tagright.gif) no-repeat right bottom; height:23px; padding:0px 10px; line-height:23px; color:#999}
    #tags li.emptyTag { width:4px; background:none}
    #tags li.selectTag { background-position: left top; position:relative; height:25px; margin-bottom:-2px}
    #tags li.selectTag a { background-position: right top; color:#000; height:25px; line-height:25px;}
    #tagContent { padding:1px; background-color:#fff; border:1px solid #aecbd4;}
    .tagContent { background:url(images/bg.gif) repeat-x; height:350px; padding:10px; color:#474747; width:576px; display:none}
    #tagContent div.selectTag{ display:block}

    </style>
    </head>
    <body>
    <h1>标签示例</h1>
    <ol>
    <li>使用 JS+DIV 实现</li>
    <li>标签宽度随文字的数量自适应</li>
    <li>支持 IE、Firefox</li>
    <li><a href="http://www.happyshow.org/article.asp?id=131" target="_blank">查看此示例的详细</a></li>
    <li><a href="http://www.happyshow.org/article.asp?id=87" target="_blank">查看旧版本</a></li>
    <li><strong>更新时间:2006-11-08</strong></li>

    </ol>
    <div id="con">
    <ul id="tags">
    <li><a href="javascrīpt:void(0)" ōnclick="selectTag('tagContent0',this)">标签一</a></li>
    <li class="selectTag"><a href="javascrīpt:void(0)" ōnclick="selectTag('tagContent1',this)">标签二</a></li>
    <li><a href="javascrīpt:void(0)" ōnclick="selectTag('tagContent2',this)">自适应宽度的标签</a></li>
    </ul>
    <div id="tagContent">
    <div id="tagContent0" class="tagContent">第一个标签的内容</div>
    <div id="tagContent1" class="tagContent selectTag">第二个标签的内容<p>标签背景图1:<img src="images/tagleft.gif" align="top"><br>标签背景图2:<img src="images/tagright.gif" align="top"><br>内容渐变背景图(1象素宽):<img src="images/bg.gif" align="top"></p></div>
    <div id="tagContent2" class="tagContent">第三个标签的内容<p>放大观看标签背景图:<img src="images/tagleft.gif" align="top" width="300" height="100"></p></div>
    </div>
    </div>
    <scrīpt type="text/javascrīpt">
    function selectTag(showContent,selfObj){
    // 操作标签
    var tag = document.getElementById("tags").getElementsByTagName("li");
    var taglength = tag.length;
    for(i=0; i<taglength; i++){
    tag[i].className = "";
    }
    selfObj.parentNode.className = "selectTag";
    // 操作内容
    for(i=0; j=document.getElementById("tagContent"+i); i++){
    j.style.display = "none";
    }
    document.getElementById(showContent).style.display = "block";


    }
    </scrīpt>
    </body>
    </html>
  • J2EE上传文件代码(STRUTS自带包)

    2008-7-15

    J2EE上传文件代码(STRUTS自带包)
    2006年10月30日 星期一 上午 08:22

    JSP页面


    <%@ page language="java" pageEncoding="GB2312"%>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html:html lang="true">
      <head>
        <html:base />
       
        <title>MyJsp.jsp</title>
       
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">   
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="descrīption" content="This is my page">
      </head>
     
      <body>
        文件上传 <br>
        <form action="uploadAction.do" method="post" enctype="multipart/form-data">  
        <INPUT type="file" name="file"/><br>
        <INPUT type="submit" value="上传"/>  
        </form>
      </body>
    </html:html>


    ActionForm中代码

    package com.seavision.OurSecond.action.knowledge;//包


    import org.apache.struts.action.ActionForm;
    import org.apache.struts.upload.FormFile;

    public class UploadActionForm extends ActionForm {

     private FormFile file;

     public FormFile getFile() {
      return file;
     }

     public void setFile(FormFile file) {
      this.file = file;
     }
     
     }

    Action中代码

    package com.seavision.OurSecond.action.knowledge;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;

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

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.upload.FormFile;


    public class UploadAction extends Action {


     public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
      UploadActionForm uploadActionForm = (UploadActionForm) form;
      FormFile file=uploadActionForm.getFile();
      
    //   上传文件开始
      String message = null;
      String Suffix = file.getFileName().substring(
        file.getFileName().lastIndexOf("."));
      //判断是否为合法文件
      if (!Suffix.equals(".txt")&&!Suffix.equals(".pdf")&&!Suffix.equals(".doc")){
       //此处可以自己修改
       System.out.println("文件格式不符合..........");
       return mapping.getInputForward();
      }
      
      
      int fileSize=file.getFileSize();
      int fileMaxSize=Integer.parseInt("500000");
      if(fileSize>fileMaxSize){
     //此处可以自己修改发生错误如何处理
       System.out.println("上传文件太大了..........");
       return mapping.getInputForward();
      }  
      //下面的也都可以从ACTIONFORM中接收
      String cataID="1";
      String fileName="ceshi";
      
      File f = null;
    //此处dir可以动态从actionform中接收!
      String dir="d:\\download\\";
      
      String filepath   =new   String(dir);  
            File   pathName=new   File(filepath);  
            pathName.mkdir();  
    //        filepath   =new   String("d:/src/framework/workflow/1/");  
    //        pathName=new   File(filepath);  
    //        pathName.mkdir(); 
      //定义将文件上传到那一个文件夹中。。
      if (cataID.equals("1")) {
       f = new File(dir + fileName+Suffix);
      }else if(cataID.equals("2")){
       f = new File(dir + fileName+Suffix);
      }else{
        f = new File(dir+ fileName+Suffix);
      }
      try {
       FileOutputStream fout = new FileOutputStream(f);
       fout.write(file.getFileData());
       fout.close();
      } catch (FileNotFoundException e) {
       message = e.getMessage();
      } catch (IOException e) {
       message = e.getMessage();
      }
      // 上传文件结束
      return null;
     }

    }

     

     


  • Hibernate一对多数据关联(1)

    2008-3-21

    Hibernate一对多数据关联(1)
    2007年12月01日 星期六 23:13
    一对多数据关联

    一.单向一对多数据关联
    一个用户有多个地址,在用户类TUser中包含地址类TAddress集合。

    1.数据模型

    2.表定义sql
    use sample;

    DROP TABLE T_Address;
    DROP TABLE T_User;

    CREATE TABLE T_User (
            id
    INT NOT NULL AUTO_INCREMENT
          , name
    VARCHAR(50)
          , age
    INT
          ,
    PRIMARY KEY (id)
    );

    CREATE TABLE T_Address (
            id
    INT NOT NULL AUTO_INCREMENT
          , address
    VARCHAR(200)
          , zipcode
    VARCHAR(10)
          , tel
    VARCHAR(20)
          , type
    VARCHAR(20)
          ,
    user_id INT NOT NULL
          , idx
    INT
          ,
    PRIMARY KEY (id)
          ,
    INDEX (user_id)
          ,
    CONSTRAINT FK_T_Address_1 FOREIGN KEY (user_id)
                      
    REFERENCES T_User (id)
    );


    3.POJO类
    TUser.java
    package cn.blogjava.start;

    import java.util.Set;

    public class TUser  implements java.io.Serializable {
        
    // Fields    
         private Integer id;
         
    private Integer age;
         
    private String name;
         
    private Set address;


        
    // Constructors

        
    public Integer getAge() {
            
    return age;
         }

        
    public void setAge(Integer age) {
            
    this.age = age;
         }


        
    public Set getAddress() {
            
    return address;
         }

        
    public void setAddress(Set address) {
            
    this.address = address;
         }

        
    /** default constructor */
        
    public TUser() {
         }
        
        
    /** constructor with id */
        
    public TUser(Integer id) {
            
    this.id = id;
         }

        
    // Property accessors

        
    public Integer getId() {
            
    return this.id;
         }
        
        
    public void setId(Integer id) {
            
    this.id = id;
         }

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

    TAddress.java
    package cn.blogjava.start;

    import java.io.Serializable;

    public class TAddress implements Serializable {
        
        
    private Integer id;
        
    private String address;
        
    private String zipcode;
        
    private String tel;
        
    private String type;
        
    private Integer userId;
        
    private Integer idx;
        
        
    public Integer getId() {
            
    return id;
         }
        
    public void setId(Integer id) {
            
    this.id = id;
         }
        
    public String getAddress() {
            
    return address;
         }
        
    public void setAddress(String address) {
            
    this.address = address;
         }
        
    public Integer getIdx() {
            
    return idx;
         }
        
    public void setIdx(Integer idx) {
            
    this.idx = idx;
         }
        
    public String getTel() {
            
    return tel;
         }
        
    public void setTel(String tel) {
            
    this.tel = tel;
         }
        
    public String getType() {
            
    return type;
         }
        
    public void setType(String type) {
            
    this.type = type;
         }
        
    public Integer getUserId() {
            
    return userId;
         }
        
    public void setUserId(Integer userId) {
            
    this.userId = userId;
         }
        
    public String getZipcode() {
            
    return zipcode;
         }
        
    public void setZipcode(String zipcode) {
            
    this.zipcode = zipcode;
         }

    }
    3.配置文件
    TUser.hbm.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"
    >
    <hibernate-mapping>
        
    <class name="cn.blogjava.start.TUser" table="T_User" catalog="sample"
          dynamic-update
    ="true" dynamic-insert="true"
        
    >
            
    <id name="id" type="integer">
                
    <column name="id" />
                
    <generator class="native" />
            
    </id>
            
    <property name="name" type="string" column="name" />
            
    <property name="age" type="java.lang.Integer" column="age" />

            
    <set name="address" table="t_address" cascade="all" order-by="zipcode asc">
                
    <key column="user_id">
                
    </key>
                
    <one-to-many class="cn.blogjava.start.TAddress" />
            
    </set>
        
    </class>
    </hibernate-mapping>

    TAddress.hbm.xml
    注意:没有配置user_id字段。
    <?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="cn.blogjava.start.TAddress" table="T_Address" catalog="sample">
            
    <id name="id" type="integer">
                
    <column name="id" />
                
    <generator class="native" />
            
    </id>
            
    <property name="address" type="string" column="address" />
            
    <property name="zipcode" type="string" column="zipcode" />
            
    <property name="tel" type="string" column="tel" />
            
    <property name="type" type="string" column="type" />
            
    <property name="idx" type="java.lang.Integer" column="idx" />
        
    </class>
    </hibernate-mapping>

    4.测试代码

    package cn.blogjava.start;

    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;

    import junit.framework.Assert;
    import junit.framework.TestCase;

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;


    public class HibernateTest extends TestCase {
        
         Session session
    = null;

        
    protected void setUp() {
            
    try {
                 Configuration config
    = new Configuration().configure();
                 SessionFactory sessionFactory
    = config.buildSessionFactory();
                 session
    = sessionFactory.openSession();
                
             }
    catch (HibernateException e) {
                 e.printStackTrace();
             }        
         }

        
    protected void tearDown() {
            
    try {
                 session.close();        
             }
    catch (HibernateException e) {
                 e.printStackTrace();
             }        
         }    
        
        
    /**
          * 对象持久化测试(Insert方法)
         
    */        
        
    public void testInsert() {
             Transaction tran
    = null;
            
    try {
            
                 TUser user
    = new TUser();
                 user.setName(
    "byf");
                 user.setAge(
    new Integer(26));
                
                 TAddress addr
    = new TAddress();
                 addr.setTel(
    "1123");
                 addr.setZipcode(
    "233123");
                 addr.setAddress(
    "HongKong");
                
                 TAddress addr2
    = new TAddress();
                 addr2.setTel(
    "139");
                 addr2.setZipcode(
    "116001");
                 addr2.setAddress(
    "dalian");            

                 TAddress addr3
    = new TAddress();
                 addr3.setTel(
    "136");
                 addr3.setZipcode(
    "100080");
                 addr3.setAddress(
    "beijing");
                
                
    //设置关联
                 HashSet set = new HashSet();
                 set.add(addr);
                 set.add(addr2);
                 set.add(addr3);
                 user.setAddress(set);
                                       
                 tran
    = session.beginTransaction();                                
                
    //插入user信息
                 session.save(user);
                 session.flush();
                 tran.commit();
                 Assert.assertEquals(user.getId().intValue()
    >0 ,true);
             }
    catch (HibernateException e) {
                 e.printStackTrace();
                 Assert.fail(e.getMessage());
                
    if(tran != null) {
                    
    try {
                         tran.rollback();
                     }
    catch (Exception e1) {
                         e1.printStackTrace();
                     }
                 }
             }
         }
        
        
    /**
          * 对象读取测试(Select方法)
         
    */            
        
    public void testSelect(){
             String hql
    = " from TUser where name='byf'";
            
    try {
                 List userList
    = session.createQuery(hql).list();
                 TUser user
    = (TUser)userList.get(0);
                 System.out.println(
    "user name is " + user.getName());
                
                
    for (Iterator iter = user.getAddress().iterator(); iter.hasNext();) {
                     TAddress addr
    = (TAddress) iter.next();
                     System.out.println(
    "user address is " + addr.getAddress());                
                 }
                 Assert.assertEquals(user.getName(),
    "byf");
             }
    catch (Exception e) {
                 e.printStackTrace();
                 Assert.fail(e.getMessage());
             }
         }
    }


    说明:
    一个问题,由于是单向关联,为了保持关联关系,我们只能通过主控方对被动方进行级联更新。如果被关联方的字段为NOT NULL属性,当Hibernate创建或者更新关联关系时,可能出现约束违例。
    例子中T_Address表中的user_id 为NOT NULL,如果在TAddress.hbm.xml映射了全部字段时。创建一个用户并赋予她地址信息,对于T_Address表而言,hibernate会执行两条sql语句来保存地址信息。

    要执行两条SQL语句,是因为关联是单向的,就是说对于TAddress对象而言,并不知道自己应该与那一个TUser对象关联,只能先将user_id设为一个空值。
    之后,根据配置文件
            <set name="address" table="t_address" cascade="all" order-by="zipcode asc">
                
    <key column="user_id">
                
    </key>
                
    <one-to-many class="cn.blogjava.start.TAddress" />
            
    </set>
    由TUser对象将自身的id赋给addr.user_id,这样导致addr属性值变动,在事物提交的时候,会进行update。

    1)当save该用户的时候,insert into t_address (user_id, address, zipcode, tel) value (null, "HongKong", "233123", "1123")2)当tx.commit()时:update t_address user_id="1", address="HongKong", zipcode="233123",tel="1123" where id=2;这样,在save user时,就会出现约束违例。调整方法:可以在定义数据表字段时候,不加NOT NULL约束。或者在开始为user_id随意赋一个非空值(因为还要update,不正确也没关系),或者将user_id字段从TAddress.hbm.xml中删除(本例就是这样实现)。但是这些都是权宜之计,用两条SQL语句完成一次数据库操作,性能低下。而双向一对多解决了这个问题。下面来实现双向关联:修改配置文件TUser.hbm.xml

    设定inverse="true",表明将TUser类作为被动类,将数据关联的维护工作交给关联对象TAddress来管理。在one-to-many模型中,将many一方设为主控方有助于性能的改善。(让总理记住每个人困难,但是每个人记住总理方便)TAddress.hbm.xml

    2.对TAddress.java做如下改造:去掉user_id字段,增加user字段,和getter,setter方法。

    4.测试代码既然TUser不维护关联关系,需要TAddress需要自己来维护TUser,所以需要addr.setUser(user);


  • POI之HSSF学习(一)

    2008-3-05

    POIHSSF学习(一)

                  最近单位的项目中要求生成Excel表格,在Jakarta中有一个子项目POI中的HSSF就可以实现这样的目的,于是花费了一点时间,学习了HSSF的基本的使用。

                  参考链接http://jakarta.apache.org/poi/index.html

                  我的学习是参照里面的Quick Guide来完成的。

               首先,理解一下一个Excel的文件的组织形式,一个Excel文件对应于一个workbook(HSSFWorkbook),一个workbook可以有多个sheetHSSFSheet)组成,一个sheet是由多个rowHSSFRow)组成,一个row是由多个cellHSSFCell)组成。

    创建一个excel文件

    HSSFWorkbook wb = new HSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();

    创建包含sheetexcel文件

    HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet1 = wb.createSheet("new sheet");//创建一个sheet
        HSSFSheet sheet2 = wb.createSheet("second sheet");//创建一个sheet
        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();

     

    我们主要的操作也就是对于一个sheet的操作,从sheet创建row,再创建cell,填充值,设置格式,等等等等。

    创建一个cell(单元格)

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("new sheet");
     
        // 创建一行,给定行号,行号是从0开始的
        HSSFRow row = sheet.createRow((short)0);
        // 创建一个单元格,给定列号,从0开始
        HSSFCell cell = row.createCell((short)0);
        cell.setCellValue(1);
     
        // Or do it on one line.
        row.createCell((short)1).setCellValue(1.2);
        row.createCell((short)2).setCellValue("This is a string");
        row.createCell((short)3).setCellValue(true);
     
        // 写入文件
        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();
     

    感觉上面的操作比较的繁琐,即使HSSFCellUtil提供的一些方法也感觉不方便,动手写了一个助手类HSSFHelper。这个方法不需要事先创建row和cell,直接进行setCellValue就可以了,在程序中会自动进行判断,如果不存在的话会创建。

            public static void setCellValue(HSSFSheet sheet, int rowNum, short colNum, String text) {

                    HSSFRow row;

                    HSSFCell cell;

                    row = HSSFCellUtil.getRow(rowNum, sheet);

                    cell = HSSFCellUtil.getCell(row,colNum);

                    cell.setCellValue(text);

            }

    对应的value可以是不同的类型,多写几个过程即可。

    注意,上面的方式如果你要对一个cell设置中文的话,是不会成功的,因为默认的设置编码是不支持中文的,你必须在setCellValue之前先这样

    cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);

    然后再

    cell.setCellValue(text);

    对于编码的选择可以参照文档,有多个编码供选择

    同样,在设置sheet的标题的时候也是

    workbook.setSheetName(0, "利用状況表", HSSFWorkbook.ENCODING_UTF_16);

    也必须指定编码。

     

    所有例子都是参照对应的Quick Start

    _____________________________________________________________________________________________

    POIHSSF学习(二)

                  以前仅仅是对一个单元格设置值,没有涉及到格式的问题,我们可以设置丰富的格式,比如一个单元格的边框,字体,颜色,背景颜色等等,(这里有一个限制,就是对于一个单元格内还不能够写入丰富文本)。

                  HSSF中专门有一个类来保存格式相关的信息HSSFCellStyle,得到一个风格描述HSSFCellStyle cs = workbook.createCellStyle();

            对一个cell设置风格cell.setCellStyle(HSSFCellStyle)

            HSSFCellStyle中包括了字体,边框,颜色等信息。在HSSF中用到的字体类是不同于JAVA中的字体类的。

                    HSSFCellStyle cs = workbook.createCellStyle();//创建一个style

                    HSSFFont littleFont = workbook.createFont();//创建一个Font

                    littleFont.setFontName("SimSun");

                    littleFont.setFontHeightInPoints((short)7);

                    cs.setFont(littleFont);//设置字体

                    cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中

                    cs.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直举重

                    cs.setBorderBottom(HSSFCellStyle.BORDER_THIN);//下边框

                    cs.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框

                    cs.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

                    cs.setBorderTop(HSSFCellStyle.BORDER_THIN);//