panda

IT高薪不是梦!!

统计

留言簿

阅读排行榜

评论排行榜

2009年7月16日 #

文件上传(FileUpload)

1.使用JAR
      jsp文件上传主要使用了两个jar包,commons-fileupload-1.2.1.jar和commons-io-1.4.jar
2.代码实现
     public class UploadServlet extends HttpServlet {

 /**
  *
  */
 private static final long serialVersionUID = 1L;

 private ServletContext sc;

 private String savePath;

 @Override
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }

 @Override
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  System.out.println("请求进来了..........");

  // 设置请求的编码
  request.setCharacterEncoding("UTF-8");

  DiskFileItemFactory factory = new DiskFileItemFactory();//创建一个磁盘文件工厂
  ServletFileUpload upload = new ServletFileUpload(factory);

  try {
   List items = upload.parseRequest(request);
   Iterator it = items.iterator();
   while (it.hasNext()) {
    FileItem item = (FileItem) it.next();

    if (item.isFormField()) {
     System.out.println("表单的参数名称:" + item.getFieldName()
       + ",对应的参数值:" + item.getString("UTF-8"));
    } else {
     // 获取文件扩展名
     String strtype = item.getName().substring(
       item.getName().length() - 3,
       item.getName().length());
     strtype = strtype.toLowerCase();

     if (strtype == "jpg" || strtype == "gif"
       || strtype == "txt") {
      if (item.getName() != null
        && !item.getName().equals("")) {
       System.out.println("上传文件的大小:" + item.getSize());
       System.out.println("上传文件的类型:"
         + item.getContentType());
       System.out.println("上传文件的名称:" + item.getName());

       System.out.println("文件的扩展名" + strtype);
       File tempFile = new File(item.getName());
       File file = new File(
         sc.getRealPath("/") + savePath, tempFile
           .getName());
       item.write(file);

       request.setAttribute("upload.message", "上传文件成功!");

      } else {
       request.setAttribute("upload.message",
         "没有选择上传文件获取格式不支持");
      }
     } else {
      request.setAttribute("upload.message", "上传文件格式不支持");
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("upload.message", "上传文件不成功!");
  }
  // 转发
  request.getRequestDispatcher("/uploadResult.jsp").forward(request,
    response);
 }

 @Override
 public void init(ServletConfig config) throws ServletException {

  savePath = config.getInitParameter("savePath");
  sc = config.getServletContext();
 }

posted @ 2009-11-08 16:30 IT追求者 阅读(156) | 评论 (0)编辑 收藏

Hibernate的多对一关联映射

1.关联映射的本质:就是将关联关系映射到数据库中,关联关系指对象模型中的一个或多个引用.

2.下面列举多对一的示例:用户和组(多个用户属于一个组)多对一关联映射是最常用的一种关联映射

   *User 类
   package com.lzy
   public class User{

   private int id;
   private String name;

  private Group group;//持有组的引用
   
   public User(){};

   //省略set,get方法
 }


  *Group类
 package com.lzy
 public class Group{
  
   private int id;

   private String name;
   //省略get,set方法
 }

3.对对象进行关系映射,这也是Hibernate中比较难的一点。
  (1)User.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 package="com.lzy">
         <class name="User" table="t_user">
               <id name="id" column="id">
                     <genarator class="native"/>
              </id>
            <property name="name" column="user_name" not-null="true"/>
            <many-to-one name="group" column="groupid"/>
        </calss>
     </hibernate-mapping>


   (2)Group.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 package="com.lzy">
         <class name="Group" table="t_group">
               <id name="id" column="id">
                     <genarator class="native"/>
              </id>
            <property name="name" column="group_name" not-null="true"/>
      </class>
   </hibernate-mapping>

4.测试

public class  Test {
   
  public static void main(String args[]){

      SessionFactory  sessionFactory=null;
      Session  session=null;
      Transaction   transaction=null;
      
      sessionFactory = HibernateUtil.getSessionFactory();// 创建一个会话工厂
      session = sessionFactory.openSession();// 创建一个会话实例
      transaction = session.beginTransaction();// 申明一个事务

  User user= new User();
  Group group = new Group();

  user.setName("龙一");

  group.setName("中南大学");
  user.setGroup(group);

  try {

   transaction.begin();
   session.save(user);
   transaction.commit();

  } catch (Exception e) {
   e.printStackTrace();
  }


   }
}

posted @ 2009-10-12 17:56 IT追求者 阅读(1412) | 评论 (2)编辑 收藏

struts logic标签使用详解

Logic 比较标签(一)

1.<logic:equal>

判断变量是否与指定的常量相等。例如:

     <%

       pageContext.setAttribute("test",new Integer(100));

     %>

     <logic:equal value="100" name="test">

         test=100     </logic:equal>

2.<logic:greaterThan>

判断常量变量是否与指定的常量不相等。

<html:link page="/greaterThan.jsp?test=123456">添加参数</html:link> //传值

<logic:greaterThan value="12347" parameter="test">

       true

</logic:greaterThan>

下面类似

3.<logic:greaterEqual>

判断变量大小是否等于指定的常量。

4.<logic:lessThan>

判断变量是否小于指定的常量。

5.<logic:lessEqual>

判断变量是否小于等于指定的常量。

Struts logic标签(二)

循环遍历标签<logic:iterate>

该标签用于在页面中创建一个循环,以次来遍历数组、Collection、Map这样的对象。在Struts中经常用到!

例如:

<%

String []testArray={"str0","str1","str2","str3","str4","str5"};

pageContext.setAttribute("test",testArray);

%>

<logic:iterate id="array" name="test">

        <bean:write name="array"/>

</logic:iterate>

首先定义了一个字符串数组,并为其初始化。接着,将该数组存入pageContext对象中,命名为test1。然后使用logic:iterate标记的name属性指定了该数组,并使用id来引用它,同时使用bean;write标记来将其显示出来。

还可以通过length属性指定输出元素的个数,offset属性指定从第几个元素开始输出。例如:

<logic:iterate id="array1" name="test1" length="3" offset="2">

<bean:write name="array1"/><br>

</logic:iterate>

Struts logic标签(三)

<logic:match>

<logic:notmatch>

该标签用于判断变量中是否或者是否不包含指定的常量字符串。例如:

<%

        pageContext.setAttribute("test","helloWord");

%>

<logic:match value="hello" name="test">

       hello 在helloWord中

</logic:match>

Match标记还有一个重要属性,就是location属性。location属性所能取的值只有两个,一个是"start",另一个是"end"。例如:

<logic:match value="hello" name="test" location="start">

          helloWord以 hello开头

</logic:match>

Struts logic存在标签(四)

<logic:present>

<logic:notpresent>

<logic:messagePresent>

<logic:messageNotPresent>

<logic:present>和<logic:notpresent>标签主要用于判断所指定的对象是否存在;

例如:

<%

pageContext.setAttribute("test","testString");

%>

<logic:present name="test">

        true  

</logic:present>

<logic:present>和<logic:notpresent>标记有以下几个常用属性:

header属性:     判断是否存在header属性所指定的header信息。

parameter属性:判断是否存在parameter属性指定的请求参数。

cookie属性:     判断cookie属性所指定的同名cookie对象是否存在。

name属性:       判断name属性所指定的变量是否存在。

property属性:和name属性同时使用,当name属性所指定的变量是一个JavaBean时,判断property属性所指定的对象属性是否存在。

<%

       Cookie cookie=new Cookie("name","value");

       response.addCookie(cookie);

%>

<logic:present cookie="name">

        true

</logic:present>

<logic:messagePresent>和<logic:messageNotPresent>这两个标记是来判断是否在request内存在特定的ActionMessages或ActionErrors对象。它们有几个常用的属性:

name属性:     指定了ActionMessages在request对象内存储时的key值。

message属性:message属性有两种取值。当其为true时,表示使用Globals.MESSAGE_KEY做为从request对象中获取ActionMessages的key值,此时无论name指定什么都无效;当其为false时,则表示需要根据name属性所指定的值做为从request对象中获取ActionMessages的key

值,倘若此时未设置name属性的值,则使用默认的Globals.ERROR_KEY。

property属性:指定ActionMessages对象中某条特定消息的key值。

例如:

      <%

         ActionErrors errors = new ActionErrors();

         errors.add("totallylost", new ActionMessage("application.totally.lost"));

         request.setAttribute(Globals.ERROR_KEY, errors);

         request.setAttribute("myerrors", errors);

      %>

         <logic:messagesPresent name="myerrors">

           Yes

         </logic:messagesPresent>

Struts logic判空标签(五)

<logic:empty>

<logic:notEmpty>

该标签用于判断指定的字符是否为空。

例如:

      <%

        pageContext.setAttribute("test","");

      %>

  

     <logic:empty name="test">

         test 为空

     </logic:empty>

Struts logic转发和重定向标签(六)

1.<logic:foward>转发标签

该标签用于进行全局转发,使用该标签的页面一般不再编写其他内容,因为随着转发,页面将跳转,原页面中的内容也没有意义了。例如:

      this is a test

<logic:forward name="welcome"/>

     this is a new test

2.<logic:redirect>重定向标签

该标签用于进行重定向。具有属性:

href属性:     将页面重定向到href指定的完整外部链接。

page属性:     该属性指定一个本应用内的一个网页,标记将页面重定向到这个新的网页。

forward属性:该属性与struts-config.xml中的<global-forward>内的子项相对应。即将页面重定向到forward所指定的资源。

posted @ 2009-07-16 23:51 IT追求者 阅读(504) | 评论 (0)编辑 收藏

struts bean标签使用详解

Bean 标签库
        此标签库和Java Bean有很强的关联性,设计的本意是要在JSP 和JavaBean 之间提供一个接口。Struts 提供了一套小巧有用的标签库来操纵JavaBean和相关的对象:cookie、 header、 parameter、 define、write、message、 include、page、resource、size、struts。
-------------------------------
-------------------------------
bean:cookie、bean:header、bean:parameter
这三个标签用来重新得到cookie, request header和request parameter。
bean:header和bean:parameter标签定义了一个字符串;bean:cookie标签定义了一个Cookie对象。你可以使用value属性做为默认值。如果找不到指定的值,且默认值没有设定的话,会抛出一个request time异常。如果你期望返回多个值的话,可把multiple属性设为true。
<bean:cookie id="sessionID" name="JSESSIONID" value="JSESSIONID-ISUNDEFINED"/>
// 这段代码定义了一个名为sessionID的脚本变量,如果找不到一个名为JSESSIONID的cookie,那sessionID


下面代码会输出一些Cookie对象的一些属性:
<jsp:getProperty name="sessionID " property="comment"/> …
<jsp:getProperty name="sessionID" property="domain"/> …
<jsp:getProperty name="sessionID" property="maxAge"/> …
<jsp:getProperty name="sessionID" property="path"/> …
<jsp:getProperty name="sessionID" property="value"/> …
<jsp:getProperty name="sessionID" property="version"/> …

下面是在request中输出所有header的例子:
<%
          java.util.Enumeration names =((HttpServletRequest) request).getHeaderNames();
%>

<%
          while (names.hasMoreElements()) {
          String name = (String) names.nextElement();
%>
<bean:header id="head" name="<%= name %>"/>
… <%= name %>
… <%= head %>

<%
          }
%>

下面是parameter的例子:
<bean:parameter id="param1" name="param1"/>
<bean:parameter id="param2" name="param2" multiple="true"/>    // 此处定义了一个param2[]。
<bean:parameter id="param3" name="param3" value="UNKNOWN VALUE"/>

于其它标签结合使用:
<bean:header id="browser" name="User-Agent"/>
<P>You are viewing this page with: <bean:write name="browser"/></P>
----------------------------------------------------------------------------------------------------------------------------------
<bean:cookie id="username" name="UserName" scope="session"
value="New User" />
<P>Welcome <bean:write name="username" property="value"/!</P>
    // 根据cookie创建一个新的Bean,如果用户名称已经存储在cookie中,它就不显示为一个新用户。
-------------------------------
-------------------------------
bean:define:有三个用途。
一是定义新字符串常量:
<bean:define id="foo" value="This is a new String"/>
<bean:define id="bar" value='<%= "Hello, " + user.getName() %>'/>
<bean:define id="last" scope="session" value='<%= request.getRequestURI() %>'/>
二是复制一个现有的bean给新的bean:
<bean:define id="foo" name="bar"/>   
<bean:define id="baz" name="bop" type="com.mycompany.MyClass"/>    //定义脚本变量的类型,默认为Object   
三是复制一个现有的bean的属性给新的bean:
<bean:define id="bop" name="user" property="role[3].name"/>
    <bean:define id="foo" name="bar" property="baz" scope="request"    toScope="session"/>
    //toScope属性指新bean的scope,默认为page  
上段代码的意思是把名为bar的bean的baz属性赋值给foo,foo的类型为String(默认)。
-------------------------------
-------------------------------
bean:include
这个标签和bean:include标签和相似,不同点就是它定义了一个可以复用的脚本变量。用id属性命名一个新的脚本变量,还支持forward、href、page和transaction.属性,和html:link中的属性意义一样。
<bean:include id="footerSpacer"    page="/long/path/footerSpacer.jsp"/>
然后你能够在多个地方(scope为page)调用:
<bean:write name="footerSpacer" />

-------------------------------
-------------------------------
bean:message
用来实现对国际化的支持的一个标签,配合java.util数据包中定义的Locale和ResourceBundle类来完成这个任务,用java.text.MessageFormat类配置消息的格式。
    首先要指定资源文件的名称。这个文件会包含用默认语言编写的在程序中会出现的所有消息,这些消息以“关键字-值”的形式存储。文件需要存储在类路径下,路径要作为初始化参数传送给ActionServlet。
    实现国际化的规定:所有的资源文件必须都存储在基本资源文件所在的目录中。基本资源文件包含的是用默认地区语言-本地语言编写的消息。如果基本资源文件的名称是ApplicationResources.properties,那么用其他特定语言编写的资源文件的名称就应该是ApplicationResources_xx.properties(xx为ISO编码,如英语是en)。因此这些文件应包含相同的关键字,但关键字的值是用特定语言编写的。
    然后,ActionServlet的区域初始化参数必须与一个true值一起传送,这样ActionServlet就会在用户会话中的Action.LOCALE_KEY关键字下存储一个特定用户计算机的区域对象。现在可以运行一个国际化的web站点,它可以根据用户计算机上的设置的区域自动以相应的语言显示。

使用特定的字符串来替换部分消息:
在资源文件中的定义:info.myKey = The numbers entered are {0},{1},{2},{3}
标记的使用:<bean:message key="info.myKey" arg0="5" arg1="6" arg2="7" arg3="8"/>
Jsp页面的显示:The numbers entered are 5,6,7,8    // 最多支持4个参数
-------------------------------

-------------------------------
   bean:page:把Jsp中的内部对象做为脚本变量。
<bean:page id="requestObj" property="request"/>
-------------------------------
-------------------------------
bean:resource:获得应用程序的资源,这个资源可以是一个String或从java.io.InputStream中读入。使用ServletContext.getResource()ServletContext.getResourceAsStream() 方法检索web应用中的资源,如果在检索资源时发生问题,就会产生一个ruquest time异常。
<bean:resource id="webxml" name="/WEB-INF/web.xml"/>
使用input属性时,资源会做为一个InputStream,如果不指定就被当成一个String。

-------------------------------
-------------------------------
bean:size:得到存储在array、collection或map中的数目,类型为java.lang.Integer。
<bean:size id="count" name="employees" />
-------------------------------
-------------------------------
bean:struts:复制Struct 对象(三种类型)给新的bean,scope为page。
<bean:struts id="form" formBean="CustomerForm"/>   
<bean:struts id="fwd" forward="success"/>
<bean:struts id="map" mapping="/saveCustomer"/>
-------------------------------
-------------------------------
bean:write:以字符串形式输出bean的属性值。
filter属性:设为true时,将HTML保留字转换为实体("<" 转换为 &lt);
ignore属性:如果对象不存在,不会抛出异常。
<bean:write name="userRegistration" property="email" scope="request"/>

posted @ 2009-07-16 23:13 IT追求者 阅读(499) | 评论 (0)编辑 收藏

struts Html标签使用详解

1.html:form 标签
       该标签的用法必须遵循很多规则.
        (1)首先标签中必须包含一个action属性,action属性是该标签唯一一个必须的属性.如果没有该属性jsp会抛出一个异常,     之后你必须给
action属性一个有效的值,这个值也就是对应struts配置文件(struts-config.xml)中的action标签中的type属性值.
          例如:jsp页面中有:<html:form action="/login">
                   则struts-config.xml文件中:
                                                                  <action-mapping>
                                                                        <action type="/login"
                                                                                      type="对应事件处理类的路径"
                                                                                      name="对应的formbean"
                                                                                       />
                                                                    </action-mapping>
       (2)html:form标签还必须遵循一个规则:
                            任何包含在<form>中用来接收用户输入的标签(<text>、<password>、<hidden>、<textarea>、<radio>、<checkbox>、<select>
)必须在相关的form bean中有一个指定的属性值.例如,如果你有一个属性值被指定为“username”的<text>标签,那么相关的form bean中也
必须有一个名为“username”的属性。输入<text>标签中的值会被用于生成form bean的userName属性。

2.html:text标签
          html:text标签是一个生成文本框的标签,它必须包含一个和form bean的相同属性的对应的"property"属性.该标签只有嵌套在form中才有效.


3.html:password标签

        html:password标签是用来显示口令的文本框,它也必须包含一个和form bean的相同属性对应的"property"属性,该标签中的
         一个很重要的属性是“redisplay”,它用于重新显示以前输入到这个区域中的值。该属性的缺省值为true。然而,为了
       使password不能被重新显示,你或许希望将该属性的值设为false。
        例如:<html:password property="password"/>


4.html:hadden标签
          html:hadden是生成一个隐藏的输入文本区域,它必须包含和相关form bean中的相同属性对应的“property”属性。该标签也必须嵌套在form中才有效.
          例如:<html:hadden property="value"/>


5.<html:textarea>标签 
        <html:textarea>标签主要是生成一个文本域,它必须包含和相关form bean中相同属性对应的"property"属性.该标签也必须嵌套在form中才有效.
        例如:<html:textarea property="content"
                                          cols="10"
                                          rows="5"/>

6.<html:radio>标签

            <html:radio>标签是用于显示一个单选按钮.它必须包含"value"值
           例如:<html:radio property="title" value="1"/>1
                     <html:radio property="title" value="2"/>2
                     <html:radio property="title" value="3"/>3



7.<html:checkbox>标签


        <html:checkbox>标签用于显示checkbox类型的输入区域。比如: <html:checkbox property= 
   "notify">Please send me notification 


8.<html:submit>标签

            <html:submit>标签是用于提交按钮.
            例如:<html:submit value="提交"/>



9.<html:reset>标签

            <html:reset>标签主要是用于重置按钮


10.<html:option>标签

               <option>标签用于显示select box中的一个选项。参照下面的<select>标签。 


11.<html:select>标签

                <html:select>标签主要是用于显示下拉列表,它也必须嵌套在form中才有效
                例如:
                        <html:select  property="color" size="3">
                                      <html:option  value="red">red</html:option>
                                      <html:option value="green">green</html:option>
                                       <html:option value="blue">blue</html:option>

 




           



            








 

posted @ 2009-07-16 22:00 IT追求者 阅读(1615) | 评论 (0)编辑 收藏