hyljava

          #

          JavaSE讀取Properties文件的六種方法

          使用JavaSEAPI讀取Properties文件的六種方法

           

          1。使用java.util.Properties類的load()方法

          示例:InputStreamin=lnewBufferedInputStream(newFileInputStream(name));

          Propertiesp=newProperties();

          p.load(in);

           

          2。使用java.util.ResourceBundle類的getBundle()方法

          示例:ResourceBundlerb=ResourceBundle.getBundle(name,Locale.getDefault());

           

          3。使用java.util.PropertyResourceBundle類的構造函數

          示例:InputStreamin=newBufferedInputStream(newFileInputStream(name));

          ResourceBundlerb=newPropertyResourceBundle(in);

           

          4。使用class變量的getResourceAsStream()方法

          示例:InputStreamin=JProperties.class.getResourceAsStream(name);

          Propertiesp=newProperties();

          p.load(in);

           

          5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法

          示例:InputStreamin=JProperties.class.getClassLoader().getResourceAsStream(name);

          Propertiesp=newProperties();

          p.load(in);

           

          6。使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態方法

          示例:InputStreamin=ClassLoader.getSystemResourceAsStream(name);

          Propertiesp=newProperties();

          p.load(in);

          補充

          Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法

          示例:InputStreamin=context.getResourceAsStream(path);

          Propertiesp=newProperties();

          p.load(in);

          posted @ 2012-11-16 15:24 何云隆 閱讀(1429) | 評論 (0)編輯 收藏

          JDBC另一次封裝

          jdbc繼續改進版
          /**
           * @author sign
           * @describe 改進第三版
           *
           */
          import java.sql.Connection;
          import java.sql.DriverManager;
          import java.sql.ResultSet;
          import java.sql.ResultSetMetaData;
          import java.sql.SQLException;
          import java.sql.Statement;
          import java.util.LinkedList;
          import java.util.Map;
          import java.util.TreeMap;

          public class JDBCUtil {
          Connection conn=null;
          Statement stmt=null;
          ResultSet rs=null;
          String url="jdbc:mysql://localhost:3306/theatermanagement";
          String user="root";
          String psw="root";

          static{
           try {
            Class.forName("com.mysql.jdbc.Driver");
            
           } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }
           
           }

            public Connection getConn(){
           
             try {
              conn=DriverManager.getConnection(url, user, psw);
           } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }
           return conn;
           }
           
            public int update(String sql){
             try {
            stmt=this.getConn().createStatement();
            return stmt.executeUpdate(sql);
           } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return -1;
           }finally{
            release();
            
           }

            }
             public LinkedList<Map<String,Object>> query(String sql){
              LinkedList<Map<String,Object>> list=new LinkedList<Map<String,Object>>();
              try {
             stmt=getConn().createStatement();
             rs=stmt.executeQuery(sql);
             ResultSetMetaData rsmd=rs.getMetaData();
             int count=rsmd.getColumnCount();
             
             while(rs.next()){
              Map<String,Object> map=new TreeMap<String,Object>();
              for (int i = 0; i < count; i++) {
               String key=rsmd.getColumnName(i+1);
               String keyy="";
               if(key.equals("")){// 聚合函數bug
                System.out.println("聚合函數bug"+key);
                keyy="count";
                Object value=rs.getObject(1);
                map.put(keyy, value);
               }else{
                Object value=rs.getObject(key);
                map.put(key, value);
               }
              }
              list.add(map);
             }
            } catch (SQLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
            }finally{
             release();
            }
            return list;
              
             }
             /**批量更新*/
             public void excuteBatch(String[] sqls){
              conn=this.getConn();
              
              /**設置提交模式為手動提交*/
              try{
               conn.setAutoCommit(false);
               stmt=conn.createStatement();
               for(String sql:sqls){
                stmt.addBatch(sql);
               }
               stmt.executeBatch();
               /**手動提交*/
               conn.commit();//事務
              }catch(SQLException e){
               e.printStackTrace();
              }finally{
               release();
              }
             }
             
             /**釋放資源*/
            public void release(){
             if(rs!=null){
              try {
              rs.close();
             } catch (SQLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
             }
             if(stmt!=null){
              try {
              stmt.close();
             } catch (SQLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
             }
             if(conn!=null){
              try {
              conn.close();
             } catch (SQLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
             
             }
            
            }
          }

          posted @ 2012-10-15 13:09 何云隆 閱讀(1370) | 評論 (1)編輯 收藏

          枚舉類型(enum)在Switch中的使用以及遍歷枚舉類型(enum)中的內容

          枚舉類型(enum)在Switch中的使用以及遍歷枚舉類型(enum)中的內容
          public class EnumDemo {
           
           //定義枚舉類型
           enum Month {  
            January, February, March, April, May, June, July,August,September,October,November,December
           }
           
           public static void main(String[] args) {
            Month mon = Month.August;
            switch (mon) {  
            case August:   
                System.out.println("這是個旅游的季節");   
                break;  
            case December:   
                System.out.println("這是個滑雪的季節");   
                break;  
            }
            //循環遍歷枚舉類型Month
            for (Month month : Month.values()) {  
                System.out.println(month + ", 順序: " + month.ordinal());  
            }
           }

          }

          posted @ 2012-09-25 14:55 何云隆 閱讀(3524) | 評論 (0)編輯 收藏

          人生區段劃分

          有一天,神創造了一頭牛。神對牛說:“你要整天在田里替農夫耕田,供應牛奶給人類飲用。你要工作直至日落,而你只能吃草。我給你50年的壽命。”
            ??棺h道:“我這么辛苦,還只能吃草,我只要20年壽命,余下的還給你。”   神答應了。
            第二天,神創造了猴子。
            神跟猴子說:“你要娛樂人類,令他們歡笑,你要表演翻斤斗,而你只能吃香蕉。我給你20年的壽命。”
            猴子抗議:“要引人發笑,表演雜技,還要翻斤斗,這么辛苦,我活10年好了。”   神答應了。

            第三天,神創造了狗?! ∩駥氛f:“你要站在門口吠,吃主人吃剩的東西。我給你25年的壽命。”
            狗抗議道:“整天坐在門口吠,我要15年好了,余下的還給你。”   神答應了。

            第四天,神創造了人?! ∩駥θ苏f:“你只需要睡覺、吃東西和玩耍,不用做任何事情,只需要盡情地享受生命,我給你20年的壽命。”
            人抗議道:“這么好的生活只有20年,太短!”
            神沒說話?! ∪藢ι裾f:“這樣吧。牛還了30年給你,猴子還了10年,狗也還了10年,這些都給我好了,那我就能活到70歲。”
            神答應了?! ∵@就是為什么我們的頭20年只需吃飯、睡覺和玩耍;之后的30年,我們像一條牛整天工作養家;接著的10年,我們退休了,不得不像只猴子表演雜耍來娛樂自己的孫兒;最后的10年,整天留在家里,像一條狗坐在門口看門……

          posted @ 2012-09-24 21:53 何云隆 閱讀(219) | 評論 (0)編輯 收藏

          Write operations are not allowed in read-only mode 只讀模式下(FlushMode.NEVER/MANUAL)寫操作不允

          Write operations are not allowed in read-only mode 只讀模式下(FlushMode.NEVER/MANUAL)寫操作不允

          org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

          問題只讀模式下(FlushMode.NEVER/MANUAL)寫操作不被允許:把你的Session改成FlushMode.COMMIT/AUTO或者清除事務定義中的readOnly標記。

           

          錯誤原因:
                    OpenSessionInViewFilter在getSession的時候,會把獲取回來的session的flush mode 設為FlushMode.NEVER。然后把該sessionFactory綁定到TransactionSynchronizationManager,使request的整個過程都使用同一個session,在請求過后再接除該sessionFactory的綁定,最后closeSessionIfNecessary根據該session是否已和transaction綁定來決定是否關閉session。在這個過程中,若HibernateTemplate 發現自當前session有不是readOnly的transaction,就會獲取到FlushMode.AUTO Session,使方法擁有寫權限。也即是,如果有不是readOnly的transaction就可以由Flush.NEVER轉為Flush.AUTO,擁有insert,update,delete操作權限,如果沒有transaction,并且沒有另外人為地設flush model的話,則doFilter的整個過程都是Flush.NEVER。所以受transaction(聲明式的事務)保護的方法有寫權限,沒受保護的則沒有。

          解決方法:

          web.xml配置里添加
          <filter>
             <filter-name>OpenSessionInViewFilter</filter-name>
             <filter-class>
              org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
             </filter-class>
             <init-param>
              <param-name>sessionFactoryBeanName</param-name>
              <param-value>sessionFactory</param-value>
             </init-param>
             <init-param>
                      <param-name>singleSession</param-name>
                      <param-value>true</param-value>           
                  </init-param>
                  <init-param>
                  <param-name> flushMode </param-name>
             <param-value>AUTO </param-value>        
                  </init-param>
          </filter>
            //   。。。。


          <filter-mapping>
             <filter-name>OpenSessionInViewFilter</filter-name>
             <url-pattern>/*</url-pattern>
          </filter-mapping>

           

          如果在交給spring 管理的情況下,在beans.xml 里的配置

           <bean id="txManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
           </bean>

           <aop:config>
            <aop:pointcut id="bussinessService"
             expression="execution(* com.fan.service.base.*.*(..))" />
            <aop:advisor pointcut-ref="bussinessService"
             advice-ref="txAdvice" />
           </aop:config>

           <tx:advice id="txAdvice" transaction-manager="txManager">
            <tx:attributes>
             <tx:method name="get*" read-only="false" propagation="NOT_SUPPORTED"/>
             <tx:method name="find*" read-only="false" propagation="NOT_SUPPORTED"/>
             <tx:method name="save*" propagation="REQUIRED"/> // 如果不把save update delete都配置上,
             <tx:method name="update*" propagation="REQUIRED"/> //這些操作會無效
             <tx:method name="delete*" propagation="REQUIRED"/>
            </tx:attributes>
           </tx:advice>

          posted @ 2012-09-05 11:57 何云隆 閱讀(31502) | 評論 (2)編輯 收藏

          Android的第一個應用(撥打電話)



          AndroidManifest.xml

          <?xml version="1.0" encoding="utf-8"?>
          <manifest xmlns:android=" package="com.hyl.phone" android:versionCode="1" android:versionName="1.0">
           <application android:icon="@drawable/maolv" android:label="@string/app_name">
            <activity android:name=".phoneActivity" android:label="@string/app_name">
             <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
            </activity>

           </application>
           <!-- 開發的應用適應的版本8代表Android2.2 -->
           <uses-sdk android:minSdkVersion="8" />
           <!-- 這里指定撥打電話的權限 -->
           <uses-permission android:name="android.permission.CALL_PHONE" />
          </manifest>
          hyl.xml
          <?xml version="1.0" encoding="utf-8"?>
          <resources>
            <string name="mobellabel">請輸入手機號碼</string>
              <string name="button">撥打此號碼</string>
           
          </resources>
          main.xml

          <?xml version="1.0" encoding="utf-8"?>
          <LinearLayout xmlns:android="
           android:orientation="vertical" android:layout_width="fill_parent"
           android:layout_height="fill_parent">
           <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="@string/mobellabel"
            android:id="@+id/TextView01"
            
            />


           <EditText   android:id="@+id/EditText01"
            android:layout_width="fill_parent" android:layout_height="wrap_content" />
            
           <Button android:text="@string/button" android:id="@+id/Button01"
            android:layout_width="wrap_content" android:layout_height="wrap_content" />
          </LinearLayout>



          phoneActivity.java

          package com.hyl.phone;

          import android.app.Activity;
          import android.content.Intent;
          import android.net.Uri;
          import android.os.Bundle;
          import android.view.View;
          import android.widget.Button;
          import android.widget.EditText;

          public class phoneActivity extends Activity {
              /** Called when the activity is first created. */
            private Button button;
            private EditText editText;
           public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.main);
                 
                   button=  (Button)this.findViewById(R.id.Button01);
                   editText=(EditText) this.findViewById(R.id.EditText01);
                 
                  button.setOnClickListener(new ButtonListener());
                 
              }
             
              private final class ButtonListener implements View.OnClickListener{

            public void onClick(View v) {
             String phonenum=editText.getText().toString();
             //android.intent.action.CALL=Intent.ACTION_CALL
             Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phonenum));
             startActivity(intent);
            }
               
              }

           
          }







          posted @ 2012-08-10 20:52 何云隆 閱讀(3073) | 評論 (2)編輯 收藏

          Struts2上傳下載

          JSP頁面
          <body>
            <s:fielderror></s:fielderror>
            <s:form action="uploadUploadAction" enctype="multipart/form-data"
             theme="simple">
              用戶名:<s:textfield name="userName" />
             <br />
              密碼: <s:textfield name="userPwd" />
             <br />
             <input type="file" name="file" />
             <br />
             <s:submit value="提交"></s:submit>
            </s:form> 
            <br />
          下載<a href="DownLoadAction">開始.gif</a>
           </body>
          UploadAction

           

          package com.hyl.action;

          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.InputStream;
          import java.io.OutputStream;
          import org.apache.struts2.ServletActionContext;
          import com.hyl.util.DateUtil;
          import com.opensymphony.xwork2.ActionSupport;

          public class UploadAction extends ActionSupport {
           private File file;
           private String fileFileName;
           private String fileContentType;
           private String userName;
           private String userPwd;

           public String upload() throws IOException {
            String path = ServletActionContext.getRequest().getRealPath("/upload");
            // System.out.println(path);

            InputStream is = new FileInputStream(file);
            String date = DateUtil.mailDate(new java.util.Date());
            // 截取的文件擴展名
            String fileExtenName = fileFileName
              .substring(fileFileName.indexOf('.'));
            // System.out.println("截取的文件擴展名"+fileName);

            File serverFile = new File(path, date + fileExtenName);

            OutputStream os = new FileOutputStream(serverFile);

            byte[] b = new byte[1024];

            int length = 0;

            while ((length = is.read(b)) > 0) {
             os.write(b);

            }
            os.close();
            is.close();
            return SUCCESS;
           }

           public File getFile() {
            return file;
           }

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

           public String getFileFileName() {
            return fileFileName;
           }

           public void setFileFileName(String fileFileName) {
            this.fileFileName = fileFileName;
           }

           public String getFileContentType() {
            return fileContentType;
           }

           public void setFileContentType(String fileContentType) {
            this.fileContentType = fileContentType;
           }

           public String getUserName() {
            return userName;
           }

           public void setUserName(String userName) {
            this.userName = userName;
           }

           public String getUserPwd() {
            return userPwd;
           }

           public void setUserPwd(String userPwd) {
            this.userPwd = userPwd;
           }

          }
          DownLoadAction

           

          package com.hyl.action;

          import java.io.InputStream;
          import java.io.UnsupportedEncodingException;
          import org.apache.struts2.ServletActionContext;
          import com.opensymphony.xwork2.ActionSupport;

          public class DownLoadAction extends ActionSupport {
          //下面以中文名文件實例
           //此處文件名稱由用戶輸入,此處也是動態傳參的過程
           private String picName = "開始.gif";

           public InputStream getDownLoad() throws UnsupportedEncodingException {
            //此處做一個中間變量,當重新編碼后就無法識別中文名了
            String rourseName=picName;
            //將源文件的中文名重新編碼,目的值讓Struts的配置文件中能識別到,呈現給用戶看
            picName=new String(picName.getBytes(),"iso-8859-1");
            
            System.out.println("/upload/"+rourseName);
            
            return ServletActionContext.getServletContext().getResourceAsStream(
              "/upload/"+rourseName);
            
           }

           public String execute() throws Exception {

            return super.execute();
           }

           public String getPicName() {
            return picName;
           }

           public void setPicName(String picName) {
            this.picName = picName;
           }

          }
          DateUtil

           

          package com.hyl.util;

          import java.text.SimpleDateFormat;
          import java.util.Calendar;
          import java.util.Date;
          import java.util.GregorianCalendar;

          public class DateUtil {

           public static String dateTimeChange(Date source) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String changeTime = format.format(source);
            return changeTime;
           }

           public static String shortDate(Date aDate) {
            SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
            return formatter.format(aDate);
           }

           public static String nowDate() {
            String iDate = "";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String str = formatter.format(new Date());
            String[] date = str.split("-");
            if (date.length >= 3) {
             iDate = date[0] + "/" + date[1] + "/" + date[2] + "";
            } else {
             iDate = str;
            }
            return iDate;
           }

           public static String mailDate(Date aDate) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            return formatter.format(aDate);
           }

           public static String dateParser(Date aDate) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            return formatter.format(aDate);
           }

           public static Date parser(String strDate) {
            ;
            strDate = strDate.replace("/", "-");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
             return sdf.parse(strDate);
            } catch (Exception e) {
             return null;
            }
           }

           public static Date parser(String strDate, String formatter) {
            SimpleDateFormat sdf = new SimpleDateFormat(formatter);
            try {
             return sdf.parse(strDate);
            } catch (Exception e) {
             return null;
            }
           }

           public static String parser(Date date, String formatter) {
            SimpleDateFormat sdf = new SimpleDateFormat(formatter);
            try {
             return sdf.format(date);
            } catch (Exception e) {
             return null;
            }
           }

           public static Date addMonth(Date myDate, int amount) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(myDate);
            boolean isEndDayOfMonth_old = cal
              .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
              .get(GregorianCalendar.DAY_OF_MONTH);
            cal.add(GregorianCalendar.MONTH, amount);
            boolean isEndDayOfMonth_new = cal
              .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
              .get(GregorianCalendar.DAY_OF_MONTH);
            if (isEndDayOfMonth_old && !isEndDayOfMonth_new) {
             cal.set(GregorianCalendar.DATE, cal
               .getActualMaximum(GregorianCalendar.DAY_OF_MONTH));
            }
            return cal.getTime();
           }

           public static Date addDay(Date myDate, int amount) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(myDate);
            cal.add(Calendar.DAY_OF_MONTH, amount);
            return cal.getTime();
           }

           public static Date addMinute(Date myDate, int amount) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(myDate);
            int minute = 0;
            amount = -(amount);

            if (amount > 60) {

             int hour = (int) amount / 60;

             if (hour * 60 > amount) {
              minute = hour * 60 - amount;

              cal.add(Calendar.HOUR_OF_DAY, -hour);
              cal.add(Calendar.MINUTE, minute);

             } else if (hour * 60 < amount) {

              minute = amount - hour * 60;
              cal.add(Calendar.HOUR_OF_DAY, -hour);
              cal.add(Calendar.MINUTE, -minute);

             } else {
              cal.add(Calendar.HOUR_OF_DAY, -hour);
             }

            } else {

             cal.add(Calendar.MINUTE, -amount);
            }
            return cal.getTime();
           }

           public static Date addYear(Date myDate, int amount) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(myDate);
            boolean isEndDayOfMonth_old = cal
              .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
              .get(GregorianCalendar.DAY_OF_MONTH);
            cal.add(GregorianCalendar.YEAR, amount);
            boolean isEndDayOfMonth_new = cal
              .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
              .get(GregorianCalendar.DAY_OF_MONTH);
            if (isEndDayOfMonth_old && !isEndDayOfMonth_new) {
             cal.set(GregorianCalendar.DATE, cal
               .getActualMaximum(GregorianCalendar.DAY_OF_MONTH));
            }
            return cal.getTime();
           }

           public static int getWeekDay(Date myDate) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(myDate);
            return cal.get(GregorianCalendar.DAY_OF_WEEK);
           }

           public static int getConvertWeekDay(Date myDate) {
            int day = getWeekDay(myDate);
            int result = day - 1;
            if (result == 0)
             result = 7;
            return result;
           }

           public static int getTimeFromDate(Date myDate) {
            SimpleDateFormat sdf = new SimpleDateFormat("hhmmss");
            int result = Integer.parseInt(sdf.format(myDate));
            return result;
           }

           public static long getDaysBetweenDate(Date startDate, Date endDate) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(startDate);
            cal.set(Calendar.HOUR, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            startDate = cal.getTime();
            cal.setTime(endDate);
            cal.set(Calendar.HOUR, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            return (cal.getTime().getTime() - startDate.getTime()) / 86400000;

           }

           public static String strDateTime(String str) {
            String idate = "";
            if (str != null) {
             String[] date = str.split("-");
             if (date.length >= 3) {
              idate = date[0] + "." + date[1] + "." + date[2];
             } else {
              idate = str;
             }
            }
            return idate;
           }

           public static String strDotDateTime(String str) {
            String idate = "";
            if (str != null) {
             String data0 = null;
             String[] date = str.split("-");
             if (date.length >= 3) {
              if (date[0] != null) {
               data0 = date[0].substring(2, 4);
              }
              idate = data0 + "." + date[1] + "." + date[2];
             } else {
              idate = str;
             }
            }
            return idate;
           }

           public static String bakDateTime(String str) {
            String idate = "";
            if (str != null) {
             int l1 = str.indexOf(".");
             String d1 = str.substring(0, l1);
             String s1 = str.substring(l1 + 1);
             int l2 = s1.indexOf(".");
             String d2 = s1.substring(0, l2);
             String d3 = s1.substring(l2 + 1);
             idate = d1 + "-" + d2 + "-" + d3;
            }
            return idate;
           }

           public static String strShortDateTime(String str) {
            String idate = "";
            if (str != null) {
             String[] date = str.split("-");
             if (date.length >= 3) {
              idate = date[0] + "." + date[1] + "." + date[2];
             } else {
              idate = str;
             }
             if (idate != null && idate.length() > 9) {
              idate = idate.substring(0, 10);

             }
            }
            return idate;
           }

           public static int getBetweenDayNumber(String dateA, String dateB) {
            long dayNumber = 0;
            long DAY = 24L * 60L * 60L * 1000L;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            try {
             java.util.Date d1 = df.parse(dateA);
             java.util.Date d2 = df.parse(dateB);
             dayNumber = (d2.getTime() - d1.getTime()) / DAY;
            } catch (Exception e) {
             e.printStackTrace();
            }
            return (int) dayNumber;
           }

           public static void main(String[] args) {
            System.out.println(nowDate());
           }
          }
          messageFile.properties

          struts.messages.error.file.too.large=\u6587\u4EF6\u8FC7\u5927
          struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u7C7B\u578B\u4E0D\u4E00\u81F4

          struts.xml

          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "<struts>
           <!--加載Struts的消息資源文件   value里面指定messageFile.properties的文件名字,不寫擴展名字-->
           <constant name="struts.custom.i18n.resources" value="messageFile"></constant>
           <package name="hyl" extends="struts-default">
            <!-- 上傳的Action -->
            <action name="*UploadAction" class="com.hyl.action.UploadAction"
             method="{1}">
             <result name="success">/ok.jsp</result>
             <result name="input">/index.jsp</result>
             <interceptor-ref name="fileUpload">
              <param name="allowedTypes">image/jpeg</param>
              <param name="maximumSize">102400</param>
             </interceptor-ref>
             <!-- 這個默認的攔截器必須放在自定義攔截器的下面,否則自定義攔截器不能唄調用 -->
             <interceptor-ref name="defaultStack"></interceptor-ref>
            </action>
            <!-- 下載的Action -->
            <action name="DownLoadAction" class="com.hyl.action.DownLoadAction">
             <result name="success" type="stream">
              <!-- 這里顯示的指定返回類型,像這種能被瀏覽器識別的類型會直接顯示出來,
              如果是其他類型,會以下載形式出現,
              如果去掉這個標簽,會啟用默認的text/plain     
               -->   
              <param name="contentType">image/jpeg</param>
              <!-- 此處的方法是Action中的getDownLoad方法, -->
              <param name="inputName">downLoad</param>
              <param name="contentDisposition">filename="${picName}"</param>
              <param name="bufferSize">1024</param>
             </result>
            </action>

           </package>

          </struts>   


          posted @ 2012-08-10 20:12 何云隆 閱讀(2935) | 評論 (0)編輯 收藏

          Struts2登錄攔截器

          UserLoginInterceptor 攔截器類(千萬不要寫成abstract類,開始我就寫成這樣了就是加載不上去)

          package com.hyl.inter;

          import java.util.Map;
          import javax.servlet.http.HttpServletRequest;
          import org.apache.struts2.ServletActionContext;
          import com.hyl.action.UserInfoAction;
          import com.opensymphony.xwork2.ActionInvocation;
          import com.opensymphony.xwork2.interceptor.Interceptor;

          public class UserLoginInterceptor implements Interceptor {
           public void destroy() {
            System.out.println("我是登錄攔截器銷毀");
           }

           public void init() {
            System.out.println("我是登錄驗證攔截器初始化");
           }

           public String intercept(ActionInvocation invocation) throws Exception {
            System.out.println("我正在進行登錄攔截功能");
            String result = "";
            // 判斷當前要調用的Action實例(對象) 是否是 登錄驗證的Action
            if (invocation.getAction() instanceof UserInfoAction) {
             
             result = invocation.invoke();
            } else {
             //當前要調用的不是登錄的Action
             //從session中取值,判斷是否是空(登錄)
             //登錄的Action中將登錄用戶信息存儲到session中,key值是當前的sessionID
             HttpServletRequest request = ServletActionContext.getRequest();
             Map session = invocation.getInvocationContext().getSession();
             if (session.get(request.getSession().getId()) != null) {
              result = invocation.invoke();
             } else {
              //session中如果不存在就跳到登錄頁面
              return "error";
             }
            }
            return result;
           }
          }

          Struts配置文件內容

          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "<struts>
           <package name="userInfo" namespace="/userInfo"  extends="struts-default">
            <interceptors>
             <interceptor name="userInter" class="com.hyl.inter.UserLoginInterceptor"></interceptor>
             <interceptor-stack name="myStack">
          <!--加載Struts默認攔截器-->
             <interceptor-ref name="defaultStack"></interceptor-ref>
             <interceptor-ref name="userInter"></interceptor-ref>
             </interceptor-stack>
            </interceptors>
            
            <default-interceptor-ref name="myStack"></default-interceptor-ref>

            <action name="*userInfoMan" class="com.hyl.action.UserInfoAction" method="{1}">
             <result name="success1" type="redirect">/menu.jsp</result>
             <result name="error" type="redirect">/user_login.jsp</result>
            </action>

           </package>

          </struts>   


           

          posted @ 2012-08-10 18:58 何云隆 閱讀(3361) | 評論 (1)編輯 收藏

          JAVA執行存儲過程

          以SQLServer為例
          import java.sql.CallableStatement;
          import java.sql.Connection;
          import java.sql.DriverManager;

          public class TestCall {
           public static void main(String[] args) {
            try{
             Connection conn=null;
             CallableStatement cs=null;
             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
             String url="jdbc:sqlserver://127.0.0.1:1433;databaseName=studentdb";
             conn=DriverManager.getConnection(url,"sa","sqlserver");
             String sql="{call s_insert(?,?)}";
             cs=conn.prepareCall(sql);
             cs.setString(1,"張三");
             cs.setInt(2, 12);
             int num=-1;
             num=cs.executeUpdate();
             System.out.println("num:"+num);
            }catch (Exception e) {
             e.printStackTrace();
            }
           }
          }

          posted @ 2012-07-25 19:27 何云隆 閱讀(1082) | 評論 (0)編輯 收藏

          利用百度地圖的API定位地理位置

          <!DOCTYPE html> 
          <html> 
          <head> 
          <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
          <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> 
          <title>Hello, World</title> 
          <style type="text/css"> 
          html{height:100%} 
          body{height:100%;margin:0px;padding:0px} 
          #container{height:70%}
          #container{width:50%} 
          </style> 
          <script type="text/javascript" src="
          </head> 
           
          <body> 
          <br><br><br><br><br>
          百度地圖接口 --  總結
          <br><br>
          <div id="container"></div> 
          <script type="text/javascript"> 
          var map = new BMap.Map("container");          // 創建地圖實例 


          //通過經緯度坐標來初始化地圖
          var point = new BMap.Point(125.4360909,43.78802888999);  // 創建點坐標 

          map.centerAndZoom(point, 15);                 // 初始化地圖,設置中心點坐標和地圖級別 

          //通過城市名稱來初始化地圖
          //map.centerAndZoom("長春");

          var marker = new BMap.Marker(point);        // 創建標注 
          map.addOverlay(marker);
           
          map.enableScrollWheelZoom();  // 開啟鼠標滾輪縮放 
          map.enableKeyboard();         // 開啟鍵盤控制 
          map.enableContinuousZoom();   // 開啟連續縮放效果 
          map.enableInertialDragging(); // 開啟慣性拖拽效果

          map.addControl(new BMap.NavigationControl()); //添加標準地圖控件(左上角的放大縮小左右拖拽控件)
          map.addControl(new BMap.ScaleControl());      //添加比例尺控件(左下角顯示的比例尺控件)
          map.addControl(new BMap.OverviewMapControl()); // 縮略圖控件
          map.addControl(new BMap.MapTypeControl());     //// 僅當設置城市信息時,MapTypeControl的切換功能才能可用map.setCurrentCity("北京"); 
          map.setCurrentCity("吉林省");

          //添加自定義控件

          // 定義一個控件類,即function 
          function ZoomControl(){ 
            // 設置默認??课恢煤推屏?nbsp;
            this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT; 
            this.defaultOffset = new BMap.Size(50, 10); 

           
          // 通過JavaScript的prototype屬性繼承于BMap.Control 
          ZoomControl.prototype = new BMap.Control(); 

          // 自定義控件必須實現initialize方法,并且將控件的DOM元素返回 
          // 在本方法中創建個div元素作為控件的容器,并將其添加到地圖容器中 
          ZoomControl.prototype.initialize = function(map){ 
            // 創建一個DOM元素 
            var div = document.createElement("div"); 
            // 添加文字說明 
            div.appendChild(document.createTextNode("長春工業大學人文信息學院")); 
            // 設置樣式 
            div.style.cursor = "pointer"; 
            div.style.border = "1px solid gray"; 
            div.style.backgroundColor = "white"; 
            // 綁定事件,點擊一次放大兩級 
            div.onclick = function(e){ 
              alert("長春工業大學人文信息學院");
            } 
            // 添加DOM元素到地圖中 
            map.getContainer().appendChild(div); 
            // 將DOM元素返回 
            return div; 

          // 創建控件實例 
          var myZoomCtrl = new ZoomControl(); 
          // 添加到地圖當中 
          map.addControl(myZoomCtrl); 

           

          //添加信息窗口
          var opts = { 
            width : 200,     // 信息窗口寬度 
            height: 70,     // 信息窗口高度 
            title : "長春工業大學人文信息學院"  // 信息窗口標題 

          var infoWindow = new BMap.InfoWindow("您好,歡迎來到長春工業大學人文信息學院", opts);  // 創建信息窗口對象 
          map.openInfoWindow(infoWindow, map.getCenter());      // 打開信息窗口

          </script> 
          </body> 
          </html>
          運行效果圖

           

          posted @ 2012-07-23 15:04 何云隆 閱讀(21232) | 評論 (4)編輯 收藏

          僅列出標題
          共11頁: First 上一頁 3 4 5 6 7 8 9 10 11 下一頁 
          主站蜘蛛池模板: 惠东县| 东莞市| 云阳县| 西贡区| 襄城县| 宁南县| 土默特右旗| 双牌县| 威信县| 嘉义县| 昌江| 南宫市| 丰台区| 吴忠市| 潼关县| 武山县| 柞水县| 勐海县| 新兴县| 闻喜县| 巴楚县| 和平县| 宜兴市| 遵化市| 阳春市| 五台县| 安龙县| 柘城县| 库尔勒市| 祁阳县| 嘉峪关市| 桑植县| 岳普湖县| 奉贤区| 宜城市| 洛川县| 哈巴河县| 车险| 关岭| 金秀| 交城县|