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 何云隆 阅读(1417) | 评论 (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 何云隆 阅读(1354) | 评论 (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 何云隆 阅读(3503) | 评论 (0)编辑 收藏

人生区段划分

有一天,神创造了一头牛。神对牛说:“你要整天在田里替农夫耕田,供应牛奶给人类饮用。你要工作直至日落,而你只能吃草。我给你50年的寿命。”
  牛抗议道:“我这么辛苦,还只能吃草,我只要20年寿命,余下的还给你。”   神答应了。
  第二天,神创造了猴子。
  神跟猴子说:“你要娱乐人类,令他们欢笑,你要表演翻斤斗,而你只能吃香蕉。我给你20年的寿命。”
  猴子抗议:“要引人发笑,表演杂技,还要翻斤斗,这么辛苦,我活10年好了。”   神答应了。

  第三天,神创造了狗。  神对狗说:“你要站在门口吠,吃主人吃剩的东西。我给你25年的寿命。”
  狗抗议道:“整天坐在门口吠,我要15年好了,余下的还给你。”   神答应了。

  第四天,神创造了人。  神对人说:“你只需要睡觉、吃东西和玩耍,不用做任何事情,只需要尽情地享受生命,我给你20年的寿命。”
  人抗议道:“这么好的生活只有20年,太短!”
  神没说话。  人对神说:“这样吧。牛还了30年给你,猴子还了10年,狗也还了10年,这些都给我好了,那我就能活到70岁。”
  神答应了。  这就是为什么我们的头20年只需吃饭、睡觉和玩耍;之后的30年,我们像一条牛整天工作养家;接着的10年,我们退休了,不得不像只猴子表演杂耍来娱乐自己的孙儿;最后的10年,整天留在家里,像一条狗坐在门口看门……

posted @ 2012-09-24 21:53 何云隆 阅读(199) | 评论 (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 何云隆 阅读(31460) | 评论 (2)编辑 收藏

Android的第一个应用(拨打电话)



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/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="http://schemas.android.com/apk/res/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 何云隆 阅读(3053) | 评论 (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" "http://struts.apache.org/dtds/struts-2.1.dtd">
<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 何云隆 阅读(2911) | 评论 (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" "http://struts.apache.org/dtds/struts-2.1.dtd">
<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 何云隆 阅读(3347) | 评论 (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 何云隆 阅读(1066) | 评论 (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="http://api.map.baidu.com/api?v=1.2"></script
</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(){ 
  // 设置默认停靠位置和偏移量 
  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 何云隆 阅读(21214) | 评论 (4)编辑 收藏

仅列出标题
共11页: First 上一页 3 4 5 6 7 8 9 10 11 下一页