java學習

          java學習

           

          des對文件快速加解密

          /*
           * To change this template, choose Tools | Templates
           * and open the template in the editor.
           */
          package com.kaishengit.util.desfile;

          import com.google.gson.Gson;
          import javax.crypto.KeyGenerator;
          import javax.crypto.CipherInputStream;
          import javax.crypto.Cipher;
          import javax.crypto.CipherOutputStream;
          import java.security.SecureRandom;
          import java.security.Key;
          import java.io.*;
          import java.security.*;
          import java.util.ArrayList;
          import java.util.List;

          import sun.misc.BASE64Decoder;
          import sun.misc.BASE64Encoder;

          /**
           *
           * @author Y-T測試成功
           */
          public class DesFile3 {

              //  private static final String k = "24234";
              Key key;

              public DesFile3() {
                  getKey("24234");//生成密匙
              }

              /**
               * 根據參數生成KEY
               */
              public void getKey(String strKey) {
                  try {
                      KeyGenerator _generator = KeyGenerator.getInstance("DES");
                      _generator.init(new SecureRandom(strKey.getBytes()));
                      this.key = _generator.generateKey();

                      _generator = null;
                  } catch (Exception e) {
                      throw new RuntimeException("Error initializing SqlMap class. Cause: " + e);
                  }
              }

              //加密以byte[]明文輸入,byte[]密文輸出   
              private byte[] getEncCode(byte[] byteS) {
                  byte[] byteFina = null;
                  Cipher cipher;
                  try {
                      cipher = Cipher.getInstance("DES");
                      cipher.init(Cipher.ENCRYPT_MODE, key);
                      byteFina = cipher.doFinal(byteS);
                  } catch (Exception e) {
                      e.printStackTrace();
                  } finally {
                      cipher = null;
                  }

                  return byteFina;
              }
              //  加密String明文輸入,String密文輸出 

              public String setEncString(String strMing) {
                  BASE64Encoder base64en = new BASE64Encoder();
                  String s = null;
                  try {
                      s = base64en.encode(getEncCode(strMing.getBytes("UTF8")));
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  return s;
              }

              public String setEncString(String strMing, int count) {
                  BASE64Encoder base64en = new BASE64Encoder();
                  String s = strMing;
                  if (s != null) {
                      for (int i = 0; i < count; i++) {
                          try {
                              s = base64en.encode(getEncCode(s.getBytes("UTF8")));
                          } catch (Exception e) {
                              e.printStackTrace();
                          }
                      }
                  } else {
                      return s;
                  }
                  return s;
              }
              // 解密以byte[]密文輸入,以byte[]明文輸出   

              public byte[] getDesCode(byte[] byteD) {
                  Cipher cipher;
                  byte[] byteFina = null;
                  try {
                      cipher = Cipher.getInstance("DES");
                      cipher.init(Cipher.DECRYPT_MODE, key);
                      byteFina = cipher.doFinal(byteD);
                  } catch (Exception e) {
                      e.printStackTrace();
                  } finally {
                      cipher = null;
                  }
                  return byteFina;
              }
              // 解密:以String密文輸入,String明文輸出  

              public String setDesString(String strMi) {
                  BASE64Decoder base64De = new BASE64Decoder();
                  String s = null;
                  try {
                      s = new String(getDesCode(base64De.decodeBuffer(strMi)), "UTF8");
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  return s;
              }

              public String setDesString(String strMi, int count) {
                  BASE64Decoder base64De = new BASE64Decoder();
                  String s = strMi;
                  if (s != null) {
                      for (int i = 0; i < count; i++) {
                          try {
                              s = new String(getDesCode(base64De.decodeBuffer(s)), "UTF8");
                          } catch (Exception e) {
                              e.printStackTrace();
                          }
                      }
                  } else {
                      return s;
                  }
                  return s;
              }

              /**
               * 文件file進行加密并保存目標文件destFile中
               *
               * @param file 要加密的文件 如c:/test/srcFile.txt
               * @param destFile 加密后存放的文件名 如c:/加密后文件.txt
               */
              public void fileEncrypt(String file, String destFile) throws Exception {
                  Cipher cipher = Cipher.getInstance("DES");
                  // cipher.init(Cipher.ENCRYPT_MODE, getKey());
                  cipher.init(Cipher.ENCRYPT_MODE, this.key);
                  InputStream is = new FileInputStream(file);
                  OutputStream out = new FileOutputStream(destFile);
                  CipherInputStream cis = new CipherInputStream(is, cipher);
                  byte[] buffer = new byte[1024];
                  int r;
                  while ((r = cis.read(buffer)) > 0) {
                      out.write(buffer, 0, r);
                  }
                  cis.close();
                  is.close();
                  out.close();
              }

              public void fileEncrypt(String file, String destFile, int count) throws Exception {
                  if(file!=null&&!"".equals(file)&&destFile!=null&&!"".equals(destFile)){
                      if(count==1){
                              fileEncrypt( file,  destFile);
                      }else {
                           String temp="";
                   String st=file;
                   for(int i=0;i<count;i++){
                        if(i!=(count-1)){
                           temp="src/jia"+System.currentTimeMillis();
                            fileEncrypt( st,  temp);
                     
                          File f = new File(st);
                          f.delete();
                          st=temp;
                     }else {
                            fileEncrypt( st,  destFile);
                            File f = new File(st);
                            f.delete();
                     }
                   }
                      }
                  }
             
              }

              /**
               * 文件采用DES算法解密文件
               *
               * @param file 已加密的文件 如c:/加密后文件.txt
               *         * @param destFile 解密后存放的文件名 如c:/ test/解密后文件.txt
               */
              public void fileDecrypt(String file, String dest) throws Exception {
                  Cipher cipher = Cipher.getInstance("DES");
                  cipher.init(Cipher.DECRYPT_MODE, this.key);
                  InputStream is = new FileInputStream(file);
                  OutputStream out = new FileOutputStream(dest);
                  CipherOutputStream cos = new CipherOutputStream(out, cipher);
                  byte[] buffer = new byte[1024];
                  int r;
                  while ((r = is.read(buffer)) >= 0) {
                      cos.write(buffer, 0, r);
                  }
                  cos.close();
                  out.close();
                  is.close();
              }

              public void fileDecrypt(String file, String destFile, int count) throws Exception {

                 if(file!=null&&!"".equals(file)&&destFile!=null&&!"".equals(destFile)){
                      if(count==1){
                              fileDecrypt( file,  destFile);
                      }else {
                           String temp="";
                   String st=file;
                   for(int i=0;i<count;i++){
                        if(i!=(count-1)){
                           temp="src/jie"+System.currentTimeMillis();
                            fileDecrypt( st,  temp);
                            File f = new File(st);
                            f.delete();
                            st=temp;
                     }else {
                            fileDecrypt( st,  destFile);
                            File f = new File(st);
                            f.delete();
                     }
                   }
                      }
                  }
              }

              public static void main(String[] args) throws Exception {
                  DesFile3 td = new DesFile3();
                  long begin = System.currentTimeMillis();


                  td.fileEncrypt("F:\\webservice\\webservice第一部分視頻\\02_wsimport的使用.avi", "F:\\webservice\\webservice第一部分視頻\\04",2); //加密
                 
              long jia = System.currentTimeMillis();
             System.out.println((jia-begin)/1000);
               long begin1 = System.currentTimeMillis();
                //  td.fileDecrypt("F:\\webservice\\webservice第一部分視頻\\04", "F:\\webservice\\webservice第一部分視頻\\04.a"); //解密
                     td.fileDecrypt("F:\\webservice\\webservice第一部分視頻\\04", "F:\\webservice\\webservice第一部分視頻\\04.avi",2); //解密
               long jie = System.currentTimeMillis();
                System.out.println((jie-begin1)/1000);
          //        List<User> list = new ArrayList<User>();
          //        User user = new User();
          //        user.setId(1);
          //        user.setAge(21);
          //        user.setName("楊軍威");
          //        User user1 = new User();
          //        user1.setId(2);
          //        user1.setAge(23);
          //        user1.setName("北京");
          //        list.add(user);
          //        list.add(user1);
          //        Gson gson = new Gson();
          //        String res = gson.toJson(list);
          //        System.out.println(res);
          //        System.out.println("加密==" + td.setEncString(res,2));
          //        //  td.setEncString(res);
          //        System.out.println("解密==" + td.setDesString(td.setEncString(res,2),2));
              }
          }

          posted @ 2013-09-11 14:27 楊軍威 閱讀(402) | 評論 (0)編輯 收藏

          jackson的序列化和反序列化

          package com.kaishengit.util.jackson;

          import java.io.IOException;
          import java.io.StringWriter;
          import java.io.Writer;
          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.Iterator;
          import java.util.LinkedHashMap;
          import java.util.List;
          import java.util.Map;
          import java.util.Set;

          import org.codehaus.jackson.JsonEncoding;
          import org.codehaus.jackson.JsonGenerationException;
          import org.codehaus.jackson.JsonGenerator;
          import org.codehaus.jackson.JsonParseException;
          import org.codehaus.jackson.map.JsonMappingException;
          import org.codehaus.jackson.map.ObjectMapper;
          import org.codehaus.jackson.node.JsonNodeFactory;

          public class JacksonTest {
           private static JsonGenerator jsonGenerator = null;
           private static ObjectMapper objectMapper = null;
           private static AccountBean bean = null;

           static {

            bean = new AccountBean();
            bean.setAddress("china-Guangzhou");
            bean.setEmail("hoojo_@126.com");
            bean.setId(1);
            bean.setName("hoojo");
            objectMapper = new ObjectMapper();
            try {
             jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
               System.out, JsonEncoding.UTF8);
            } catch (IOException e) {
             e.printStackTrace();
            }

           }

           // public void init() {}

           /*
            * public void destory() { try { if (jsonGenerator != null) {
            * jsonGenerator.flush(); } if (!jsonGenerator.isClosed()) {
            * jsonGenerator.close(); } jsonGenerator = null; objectMapper = null; bean
            * = null; System.gc(); } catch (IOException e) { e.printStackTrace(); } }
            */
           // JavaBean(Entity/Model)轉換成JSON
           public static void writeEntityJSON() {
            try {
             
             System.out.println("jsonGenerator"); // writeObject可以轉換java對象,eg:JavaBean/Map/List/Array等
             jsonGenerator.writeObject(bean);

             System.out.println();
             System.out.println("ObjectMapper"); // writeValue具有和writeObject相同的功能
             StringWriter strWriter = new StringWriter(); 
             objectMapper.writeValue(strWriter, bean);
             String s = strWriter.toString();
             System.out.println("-----------------------");
             System.out.println(s);
             
            } catch (IOException e) {
             e.printStackTrace();
            }
           }

           // 將Map集合轉換成Json字符串
           public static void writeMapJSON() {
            try {
             Map<String, Object> map = new HashMap<String, Object>();
             map.put("name", bean.getName());
             map.put("account", bean);
             bean = new AccountBean();
             bean.setAddress("china-Beijin");
             bean.setEmail("hoojo@qq.com");
             map.put("account2", bean);
             System.out.println("jsonGenerator");
             jsonGenerator.writeObject(map);
             System.out.println("");
             System.out.println("objectMapper");
             Writer strWriter = new StringWriter(); 
             objectMapper.writeValue(strWriter, map);
             System.out.println(strWriter.toString());
            } catch (IOException e) {
             e.printStackTrace();
            }
           }

           // 將List集合轉換成json
           public static void writeListJSON() {
            try {
             List<AccountBean> list = new ArrayList<AccountBean>();
             list.add(bean);
             bean = new AccountBean();
             bean.setId(2);
             bean.setAddress("address2");
             bean.setEmail("email2");
             bean.setName("haha2");
             list.add(bean);
             System.out.println("jsonGenerator"); // list轉換成JSON字符串
             jsonGenerator.writeObject(list);
             System.out.println();
             System.out.println("ObjectMapper"); // 用objectMapper直接返回list轉換成的JSON字符串
             System.out.println("1###" + objectMapper.writeValueAsString(list));
             System.out.print("2###"); // objectMapper list轉換成JSON字符串
             Writer strWriter = new StringWriter(); 
             objectMapper.writeValue(strWriter, list);
             System.out.println(strWriter.toString());
            } catch (IOException e) {
             e.printStackTrace();
            }
           }

           public static void writeOthersJSON() {
            try {
             String[] arr = { "a", "b", "c" };
             System.out.println("jsonGenerator");
             String str = "hello world jackson!"; // byte
             jsonGenerator.writeBinary(str.getBytes()); // boolean
             jsonGenerator.writeBoolean(true); // null
             jsonGenerator.writeNull(); // float
             jsonGenerator.writeNumber(2.2f); // char
             jsonGenerator.writeRaw("c"); // String
             jsonGenerator.writeRaw(str, 5, 10); // String
             jsonGenerator.writeRawValue(str, 5, 5); // String
             jsonGenerator.writeString(str);
             jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
             System.out.println(); // Object
             jsonGenerator.writeStartObject();// {
             jsonGenerator.writeObjectFieldStart("user");// user:{
             jsonGenerator.writeStringField("name", "jackson");// name:jackson
             jsonGenerator.writeBooleanField("sex", true);// sex:true
             jsonGenerator.writeNumberField("age", 22);// age:22
             jsonGenerator.writeEndObject();// }
             jsonGenerator.writeArrayFieldStart("infos");// infos:[
             jsonGenerator.writeNumber(22);// 22
             jsonGenerator.writeString("this is array");// this is array
             jsonGenerator.writeEndArray();// ]
             jsonGenerator.writeEndObject();// }
             AccountBean bean = new AccountBean();
             bean.setAddress("address");
             bean.setEmail("email");
             bean.setId(1);
             bean.setName("haha");
             // complex Object
             jsonGenerator.writeStartObject();// {
             jsonGenerator.writeObjectField("user", bean);// user:{bean}
             jsonGenerator.writeObjectField("infos", arr);// infos:[array]
             jsonGenerator.writeEndObject();// }
            } catch (Exception e) {
             e.printStackTrace();
            }
           }

           // 將json字符串轉換成JavaBean對象
           public static void readJson2Entity() {
            String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
            try {
             AccountBean acc = objectMapper.readValue(json, AccountBean.class);
             System.out.println(acc.getName());
             System.out.println(acc);
            } catch (JsonParseException e) {
             e.printStackTrace();
            } catch (JsonMappingException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
           }

           // 將json字符串轉換成List<Map>集合
           public static void readJson2List() {
            String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
              + "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
            try {
             List<LinkedHashMap<String, Object>> list = objectMapper.readValue(
               json, List.class);
             System.out.println(list.size());
             for (int i = 0; i < list.size(); i++) {
              Map<String, Object> map = list.get(i);
              Set<String> set = map.keySet();
              for (Iterator<String> it = set.iterator(); it.hasNext();) {
               String key = it.next();
               System.out.println(key + ":" + map.get(key));
              }
             }
            } catch (JsonParseException e) {
             e.printStackTrace();
            } catch (JsonMappingException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
           }

           // Json字符串轉換成Array數組
           public static void readJson2Array() {
            String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
              + "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
            try {
             AccountBean[] arr = objectMapper.readValue(json,
               AccountBean[].class);
             System.out.println(arr.length);
             for (int i = 0; i < arr.length; i++) {
              System.out.println(arr[i]);
             }
            } catch (JsonParseException e) {
             e.printStackTrace();
            } catch (JsonMappingException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
           }

           // Json字符串轉換成Map集合
           public static void readJson2Map() {
            String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
              + "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
            try {
             Map<String, Map<String, Object>> maps = objectMapper.readValue(
               json, Map.class);
             System.out.println(maps.size());
             Set<String> key = maps.keySet();
             Iterator<String> iter = key.iterator();
             while (iter.hasNext()) {
              String field = iter.next();
              System.out.println(field + ":" + maps.get(field));
             }
            } catch (JsonParseException e) {
             e.printStackTrace();
            } catch (JsonMappingException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
           }

           /*
            * public void writeObject2Xml() { //stax2-api-3.0.2.jar
            * System.out.println("XmlMapper"); XmlMapper xml = new XmlMapper(); try {
            * //javaBean轉換成xml //xml.writeValue(System.out, bean); StringWriter sw =
            * new StringWriter(); xml.writeValue(sw, bean);
            * System.out.println(sw.toString()); //List轉換成xml List<AccountBean> list =
            * new ArrayList<AccountBean>(); list.add(bean); list.add(bean);
            * System.out.println(xml.writeValueAsString(list)); //Map轉換xml文檔
            * Map<String, AccountBean> map = new HashMap<String, AccountBean>();
            * map.put("A", bean); map.put("B", bean);
            * System.out.println(xml.writeValueAsString(map)); } catch
            * (JsonGenerationException e) { e.printStackTrace(); } catch
            * (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) {
            * e.printStackTrace(); }}
            */

           public static void main(String[] args) {
             JacksonTest.writeEntityJSON();
            // JacksonTest.writeMapJSON();
            // JacksonTest.writeListJSON();
            // JacksonTest.writeOthersJSON();
            // JacksonTest.readJson2Entity();
            // JacksonTest.readJson2List();
            // JacksonTest.readJson2Array();
            //JacksonTest.readJson2Map();
           }

          }

          posted @ 2013-09-10 15:19 楊軍威 閱讀(4889) | 評論 (0)編輯 收藏

          jaxb的序列化和反序列化

          1.公司和雇員的實體類

          @XmlRootElement(name="company")

          public class Company {
              //   @XmlElement(name="cname")
              private String cname;
              @XmlElement(name="employee")
              private List<Employee> employees;
                 public Company(String cname,List<Employee> employees){
                 this.cname=cname;
                 this.employees=employees;
                 }
                 public Company(){}
              @XmlTransient
              public List<Employee> getEmployees() {
                  return this.employees;
              }

              public void setEmployees(List<Employee> employees) {
                  this.employees = employees;
              }
          //    public void addEmployee(Employee employee){
          //     if(employees==null){
          //            this.employees=new ArrayList<Employee>();
          //     }
          //     this.employees.add(employee);
          //    }

              public String getCname() {
                  return this.cname;
              }

              public void setCname(String cname) {
                  this.cname = cname;
              }
             
          }

          @XmlType

          public class Employee {
              @XmlElement(name="name")
              private String name;
              @XmlElement(name="id")
              private String id;
              public Employee(String name,String id){
                  this.id=id;
                  this.name=name;
              }
              public Employee(){}
           @XmlTransient
              public String getName() {
                  return name;
              }

              public void setName(String name) {
                  this.name = name;
              }
           @XmlTransient
              public String getId() {
                  return id;
              }

              public void setId(String id) {
                  this.id = id;
              }
            
          }


          測試類:

          public class Test {
                public static void main(String[] args){
                  Test.test01();
              }
              public static void test01() {
                  long l=System.currentTimeMillis();
            try {
             JAXBContext ctx = JAXBContext.newInstance(Company.class);
             Marshaller marshaller = ctx.createMarshaller();
                                  List<Employee> list=new ArrayList<Employee>();
                                  list.add(new Employee("1","1e"));
                                  list.add(new Employee("2", "2e"));
             Company c = new Company("cc",list);
                                  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                    //  marshaller.marshal( c,new FileOutputStream("src/"+l+".xml"));
              StringWriter sw = new StringWriter();
             
                marshaller.marshal(c,sw);
                System.out.println(sw.toString());
                test02(sw.toString());
            //     Unmarshaller unmarshaller = ctx.createUnmarshaller();  
               //  File file = new File("src/"+l+".xml");  
               //  Company cc = (Company)unmarshaller.unmarshal(file);  
              // //  System.out.println(cc.getCname());  
              //   System.out.println(cc.getEmployees().get(0).getName());      
              //        System.out.println(file.exists()); 
            } catch (JAXBException e) {
             e.printStackTrace();
            }
           }
               public static void test02(String xml) {
            try {
            // String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><company><employee><name>1</name><id>1e</id></employee><employee><name>2</name><id>2e</id></employee><cname>cc</cname></company>";
             JAXBContext ctx = JAXBContext.newInstance(Company.class);
             Unmarshaller um = ctx.createUnmarshaller();
             Company stu = (Company)um.unmarshal(new StringReader(xml));
             System.out.println(stu.getEmployees().get(0).getName() +","+stu.getCname());
            } catch (JAXBException e) {
             e.printStackTrace();
            }
            
           }
                  public static void test03() {
                      try{
                       JAXBContext context = JAXBContext.newInstance(Company.class);  
                  Unmarshaller unmarshaller = context.createUnmarshaller();  
                  File file = new File("src/test.xml");  
                  Company c = (Company)unmarshaller.unmarshal(file);  
                  System.out.println(c.getCname());  
                  System.out.println(c.getEmployees().get(0).getName());
                      }catch (Exception e){
                     
                      }
                      
                 // System.out.println(people.age);  
                  }
          }



          posted @ 2013-09-10 15:14 楊軍威 閱讀(475) | 評論 (0)編輯 收藏

          sql中查詢條件%%的含義

          select * from table_name
          是查詢出table_name 里所有的記錄

          select * from table_name where column_name like '%%'

          是查詢出table_name表里column_name 類似于'%%'的記錄

          由于%是代替所有,‘%%’代替所有,但并不表示代替空值,所以后一條記錄和前一條的區別是,前一條是查詢所有記錄,后一條是查詢column_name 值 不為空的所有記錄。
          %是字符通配付,必須是字符。
          select * from table_name 是查詢整個表
          select * from table_name where column_name like '%%' 查詢這個字段 NOT IS NULL

          posted @ 2013-08-27 09:52 楊軍威 閱讀(1140) | 評論 (0)編輯 收藏

          ApplicationContextAware接口的作用

          加載Spring配置文件時,如果Spring配置文件中所定義的Bean類實現了ApplicationContextAware 接口,那么在加載Spring配置文件時,會自動調用ApplicationContextAware 接口中的

          public void setApplicationContext(ApplicationContext context) throws BeansException

          方法,獲得ApplicationContext對象。

          前提必須在Spring配置文件中指定該類

          public class ApplicationContextRegister implements ApplicationContextAware {

          private Log log = LogFactory.getLog(getClass());

          public void setApplicationContext(ApplicationContext applicationContext)
             throws BeansException {
            ContextUtils.setApplicationContext(applicationContext);
            log.debug("ApplicationContext registed");
          }

          }

          public class ContextUtils {

          private static ApplicationContext applicationContext;

          private static Log log = LogFactory.getLog(ContextUtils.class);

          public static void setApplicationContext(ApplicationContext applicationContext) {
            synchronized (ContextUtils.class) {
             log.debug("setApplicationContext, notifyAll");
             ContextUtils.applicationContext = applicationContext;
             ContextUtils.class.notifyAll();
            }
          }

          public static ApplicationContext getApplicationContext() {
            synchronized (ContextUtils.class) {
             while (applicationContext == null) {
              try {
               log.debug("getApplicationContext, wait...");
               ContextUtils.class.wait(60000);
               if (applicationContext == null) {
                log.warn("Have been waiting for ApplicationContext to be set for 1 minute", new Exception());
               }
              } catch (InterruptedException ex) {
               log.debug("getApplicationContext, wait interrupted");
              }
             }
             return applicationContext;
            }
          }

          public static Object getBean(String name) {
            return getApplicationContext().getBean(name);
          }

          }

          配置文件:<bean class="com.sinotrans.framework.core.support.ApplicationContextRegister" />

          正常情況:

          1. public class AppManager extends ContextLoaderListener implements  ServletContextListener {  
          2.  
          3.     private ServletContext context;  
          4.     private WebApplicationContext webApplicationContext;  
          5.  
          6.     public void contextInitialized(ServletContextEvent sce) {  
          7.         this.context = sce.getServletContext();  
          8.         this.webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);  
          9.         this.context.setAttribute("WEBAPPLICATIONCONTEXT", webApplicationContext);       } 
          1. HttpSession session = request.getSession();  
          2. WebApplicationContext webApplicationContext = (WebApplicationContext)session.getServletContext().getAttribute("WEBAPPLICATIONCONTEXT");  
          3. UnsubscribeEmailFacade unsubscribeEmailFacade = (UnsubscribeEmailFacade)webApplicationContext.getBean("unsubscribeEmailFacade"); 

          posted @ 2013-08-23 09:29 楊軍威 閱讀(37201) | 評論 (1)編輯 收藏

          純javascript和jquery實現增刪改查

          <html>
           <head>
          <script src="jquery.js" type="text/javascript"></script>

           </head>
           <body>
            <form class="cmxform" id="commentForm" method="get" action="#"  style="float:left;position:absolute ;background-color: yellow;width:100%;height:100% " >
           <fieldset style="width:100%;height:100%">
           
             <p>
               <label for="cusername">姓名</label>
               <em>*</em><input id="cusername" name="username" size="25"   />
             </p>
             <p>
               <label for="cemail">電子郵件</label>
               <em>*</em><input id="cemail" name="email" size="25"    />
             </p>
             <p>
               <label for="curl">網址</label>
               <em>  </em><input id="curl" name="url" size="25"  value=""  />
             </p>
             <p>
               <label >價格</label>
               <em>  </em><input id="cprice" name="price" size="25"  value=""  />
             </p>
             <p>
               <label for="ccomment">你的評論</label>
               <em>*</em><textarea id="ccomment" name="comment" cols="22"  ></textarea>
             </p>
             <p>
               <input class="submit" type="button" value="提交"/>
             <input class="quxiao" type="button" value="取消"/>
             </p>
           </fieldset>
           </form>
           <div>
           <form>
              <input type="text" id="chaxun" /><input type="button" value="查詢" />
           </form>
           <div>
            <input type="button" value="全選/全不選"  id="CheckedAll"/>
            <input type="button" value="反選" id='CheckedRev' />
            <input id="add" type="button" value="新增"/>
            <input type="button" value="刪除" class="deleteall" />
           </div>
           </div>
           <table cellpadding="0" cellspacing="0" border="1" width="100%">
           <thead><tr><td>姓名</td><td>電子郵件</td><td>網址</td><td>你的評論</td><td>價格</td><td>編輯</td><td>刪除</td></tr></thead>
           <tbody>
            <tr></tr>
           </tbody>
           <tfoot>
            <tr><td>總價</td><td   colspan="6">0</td></tr>
           </tfoot>
           </table>
           </body>
            <script type="text/javascript">
            $(document).ready(function(){
            //  $("#commentForm").validate({meta: "validate"});
           $("#commentForm").hide();
           $("#add").bind("click",function(){
            
               if($("#commentForm").is(":visible")){
             $("#commentForm").hide();
            }else{
             $("#commentForm").show();
            }
           })
           var num = 1;
           $(".submit").click(function(){
           $("#commentForm").hide();
           var name = $('#cusername').val();
           var email = $('#cemail').val();
           var url = $('#curl').val();
           var price = $('#cprice').val();
           var comment = $('#ccomment').val();

           var tr = $('<tr class="'+num+'"><td class="jsname"><input type="checkbox" value="'+num+'"/>'+name+'</td><td class="jsemail">'+email+'</td><td class="jsurl">'+url+'</td><td class="jscomment">'+comment+'</td><td class="jsprice" id="'+num+'">'+price+'</td><td><a href="#" class="edit">編輯</a></td><td><a href="#" class="delete">刪除</a></td></tr>');
           $('tbody tr:eq(0)').after(tr);
           
           
           num++;
           });
           $(".quxiao").click(function(){
           $("#commentForm").hide();
           });
           $('.delete').live('click',function(){
            $(this).parent().parent().remove();
           });
           $('.edit').live('click',function(){
             var tr=$(this).parent().parent();
             var name = tr.children('.jsname').text();
             var email = tr.children('.jsemail').text();
             var url = tr.children('.jsurl').text();
             var comment = tr.children('.jscomment').text();
             var price = tr.children('.jsprice').text();
             $('#cusername').attr('value',name);
             $('#cemail').attr('value',email);
             $('#curl').attr('value',url);
             $('#cprice').attr('value',price);
             $('#ccomment').attr('value',comment);
             $("#commentForm").show();
              $(this).parent().parent().remove();
           }); 
           $('.deleteall').click(function(){
            $('input[type="checkbox"]:checked').each(function(){
              $(this).parent().parent().remove();
            });
           });
           var a = true;
            $("#CheckedAll").click(function(){
             //所有checkbox跟著全選的checkbox走。
             if(a){
             $('input[type="checkbox"]:checkbox').attr("checked", true);
             a = false;
             }else {
              $('input[type="checkbox"]:checkbox').attr("checked", false);
              a=true;
             }
             
            });
           
            $("#CheckedRev").click(function(){
              $('input[type="checkbox"]:checkbox').each(function(){
            
             this.checked=!this.checked;
              });
            });
            });
            </script>
          </html>

          posted @ 2013-08-16 16:27 楊軍威 閱讀(564) | 評論 (0)編輯 收藏

          編寫schema引入xml文件中


          myschema文件如下:
          <?xml version="1.0" encoding="UTF-8"?>
          <schema xmlns="  targetNamespace="  xmlns:tns="  elementFormDefault="qualified">
            <element name="user">
             <complexType>
              <sequence>
               <element name="id" type="int"/>
               <element name="username" type="string"/>
               <element name="time" type="date"/>
              </sequence>
             </complexType>
            </element>
          </schema>
          xml文件如下1:
          <?xml version="1.0" encoding="UTF-8"?>
          <user xmlns="
             xmlns:xsi="   xsi:schemaLocation=" <id>1</id>
           <username>zhangsan</username>
           <born>1989-12-22</born>
          </user>

          xml文件2如下:
          <?xml version="1.0" encoding="UTF-8"?>
          <user xmlns="
             xmlns:xsi="   xsi:noNamespaceSchemaLocation="01.xsd">
            <id>11</id>
            <username>lisi</username>
            <born>1988-11-11</born>
          </user>

          posted @ 2013-08-15 17:14 楊軍威 閱讀(195) | 評論 (0)編輯 收藏

          soap的基于契約優先WSDL的開發webservice流程

               摘要: -- 開發流程: 一、先寫schema或者wsdl文件 (1)新建一個項目作為服務端,在src目錄下簡歷文件夾META-INF/wsdl/mywsdl.wsdl文件。(2)在mywsdl.wsdl文件中編寫自己的內容,如下: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <wsdl:d...  閱讀全文

          posted @ 2013-08-15 13:38 楊軍威 閱讀(559) | 評論 (0)編輯 收藏

          soap消息的分析和消息的創建和傳遞和處理



          @WebService
          public interface IMyService {
           @WebResult(name="addResult")
           public int add(@WebParam(name="a")int a,@WebParam(name="b")int b);
           
           @WebResult(name="user")
           public User addUser(@WebParam(name="user")User user);
           
           @WebResult(name="user")
           public User login(@WebParam(name="username")String username,
                 @WebParam(name="password")String password)throws UserException;
           
           @WebResult(name="user")
           public List<User> list(@WebParam(header=true,name="authInfo")String authInfo);
          }

          @XmlRootElement
          public class User {
           private int id;
           private String username;
           private String nickname;
           private String password;
           public int getId() {
            return id;
           }
           public void setId(int id) {
            this.id = id;
           }
           public String getUsername() {
            return username;
           }
           public void setUsername(String username) {
            this.username = username;
           }
           public String getNickname() {
            return nickname;
           }
           public void setNickname(String nickname) {
            this.nickname = nickname;
           }
           public String getPassword() {
            return password;
           }
           public void setPassword(String password) {
            this.password = password;
           }
           public User(int id, String username, String nickname, String password) {
            super();
            this.id = id;
            this.username = username;
            this.nickname = nickname;
            this.password = password;
           }
           public User() {
            super();
           }
           
           
           
          }

          public class MyServer {

           public static void main(String[] args) {
            Endpoint.publish("http://localhost:8989/ms", new MyServiceImpl());
           }

          }



          --

           

          @WebService(endpointInterface="org.soap.service.IMyService")
          @HandlerChain(file="handler-chain.xml")
          public class MyServiceImpl implements IMyService {
           private static List<User> users = new ArrayList<User>();
           
           public MyServiceImpl() {
            users.add(new User(1,"admin","","111111"));
           }

           @Override
           public int add(int a, int b) {
            System.out.println("a+b="+(a+b));
            return a+b;
           }

           @Override
           public User addUser(User user) {
            users.add(user);
            return user;
           }

           @Override
           public User login(String username, String password) throws UserException{
            for(User user:users) {
             if(username.equals(user.getUsername())&&password.equals(user.getPassword()))
              return user;
            }
            throw new UserException("");
           }

           @Override
           public List<User> list(String authInfo) {
            System.out.println(authInfo);
            return users;
           }

          }

          public class TestSoap {
           
           private static String ns = " private static String wsdlUrl = "http://localhost:8989/ms?wsdl";
                 
                  public static void main(String[] args){
                      TestSoap.test03();
                  }

           @Test
           public static void test01() {
            try {
             //1???????創建消息工廠???
             MessageFactory factory = MessageFactory.newInstance();
             //2????根據消息工廠創建SoapMessage
             SOAPMessage message = factory.createMessage();
             //3?????創建SOAPPart
             SOAPPart part = message.getSOAPPart();
             //4??獲取SOAPENvelope
             SOAPEnvelope envelope = part.getEnvelope();
             //5??可以通過SoapEnvelope有效的獲取相應的Body和Header等信息
             SOAPBody body = envelope.getBody();
             //6???根據Qname創建相應的節點(QName就是一個帶有命名空間的節點)????????????)
             QName qname = new QName("     "add","ns");//<ns:add xmlns="http://java.zttc.edu.cn/webservice"/>
             //?如果使用以下方式進行設置,會見<>轉換為&lt;和&gt
             //body.addBodyElement(qname).setValue("<a>1</a><b>2</b>");
             SOAPBodyElement ele = body.addBodyElement(qname);
             ele.addChildElement("a").setValue("22");
             ele.addChildElement("b").setValue("33");
             //打印消息信息
             message.writeTo(System.out);
            } catch (SOAPException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
           }
           
           @Test//基于soap的消息傳遞
           public static void test02() {
            try {
             //1???創建服務(Service)
             URL url = new URL(wsdlUrl);
             QName sname = new QName(ns,"MyServiceImplService");
             Service service = Service.create(url,sname);
             
             //2????創建Dispatch
             Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
                SOAPMessage.class, Service.Mode.MESSAGE);
             
             //3????創建SOAPMessage
             SOAPMessage msg = MessageFactory.newInstance().createMessage();
             SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
             SOAPBody body = envelope.getBody();
             
             //4???創建QName來指定消息中傳遞數據????
             QName ename = new QName(ns,"add","nn");//<nn:add xmlns="xx"/>
             SOAPBodyElement ele = body.addBodyElement(ename);
             ele.addChildElement("a").setValue("22");
             ele.addChildElement("b").setValue("33");
             msg.writeTo(System.out);
             System.out.println("\n invoking.....");
             
             
             //5?通過Dispatch傳遞消息,會返回響應消息
             SOAPMessage response = dispatch.invoke(msg);
             response.writeTo(System.out);
             System.out.println("\n----------------------------------------");
             
             //??將響應的消息轉換為dom對象??
             Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
             String str = doc.getElementsByTagName("addResult").item(0).getTextContent();
             System.out.println(str);
            } catch (SOAPException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
           }
           
           @Test
           public static void test03() {
            try {
             //1?????創建服務(Service)
             URL url = new URL(wsdlUrl);
             QName sname = new QName(ns,"MyServiceImplService");
             Service service = Service.create(url,sname);
             
             //2???創建Dispatch(通過源數據的方式傳遞)
             Dispatch<Source> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
                Source.class, Service.Mode.PAYLOAD);
             //3???根據用戶對象創建相應的xml
             User user = new User(3,"zs","張三","11111");
                                  //編排user對象
             JAXBContext ctx = JAXBContext.newInstance(User.class);
             Marshaller mar = ctx.createMarshaller();
                                  //不會再創建xml的頭信息
             mar.setProperty(Marshaller.JAXB_FRAGMENT, true);
             StringWriter writer= new StringWriter();
             mar.marshal(user, writer);
             System.out.println("writer====="+writer);
             //4、封裝相應的part addUser
             String payload = "<xs:addUser xmlns:xs=\""+ns+"\">"+writer.toString()+"</xs:addUser>";
             System.out.println("payload====="+payload);
             StreamSource rs = new StreamSource(new StringReader(payload));
             
             //5?通過dispatch傳遞payload
             Source response = (Source)dispatch.invoke(rs);
             
             //6?將Source轉化為DOM進行操作,使用Transform對象轉換
             Transformer tran = TransformerFactory.newInstance().newTransformer();
             DOMResult result = new DOMResult();
             tran.transform(response, result);
             
             //7???處理相應信息(通過xpath處理)
             XPath xpath = XPathFactory.newInstance().newXPath();
             NodeList nl = (NodeList)xpath.evaluate("http://user", result.getNode(),XPathConstants.NODESET);
             User ru = (User)ctx.createUnmarshaller().unmarshal(nl.item(0));
             System.out.println(ru.getNickname());
            } catch (IOException e) {
             e.printStackTrace();
            } catch (JAXBException e) {
             e.printStackTrace();
            } catch (TransformerConfigurationException e) {
             e.printStackTrace();
            } catch (TransformerFactoryConfigurationError e) {
             e.printStackTrace();
            } catch (TransformerException e) {
             e.printStackTrace();
            } catch (XPathExpressionException e) {
             e.printStackTrace();
            }
           }

          posted @ 2013-08-13 10:04 楊軍威 閱讀(1423) | 評論 (0)編輯 收藏

          schema的筆記


          schema文件:
          <?xml version="1.0" encoding="UTF-8"?>
          <schema xmlns="  targetNamespace="  xmlns:tns="  elementFormDefault="qualified">
           <element name="user">
            <complexType>
             <sequence>
              <element name="id" type="int"/>
              <element name="username" type="string"/>
              <element name="born" type="date"/>
             </sequence>
            </complexType>
           </element>
          </schema>

          xml文件1:
          <?xml version="1.0" encoding="UTF-8"?>
          <user xmlns="
             xmlns:xsi="   xsi:schemaLocation=" <id>1</id>
           <username>zhangsan</username>
           <born>1989-12-22</born>
          </user>

          xml文件2:
          <?xml version="1.0" encoding="UTF-8"?>
          <user xmlns="
             xmlns:xsi="   xsi:noNamespaceSchemaLocation="01.xsd">
            <id>11</id>
            <username>lisi</username>
            <born>1988-11-11</born>
          </user>

          schema文件2:

          <?xml version="1.0" encoding="UTF-8"?>
          <schema xmlns="

           <element name="books">
            <complexType>
            <!-- maxOccurs表示最大出現次數 -->
             <sequence maxOccurs="unbounded">
              <element name="book">
               <complexType>
                <sequence minOccurs="1" maxOccurs="unbounded">
                 <element name="title" type="string" />
                 <element name="content" type="string" />
                 <choice>
                  <element name="author" type="string" />
                  <element name="authors">
                   <complexType>
                    <all><!-- 每個元素只能出現一次 -->
                     <element name="author" type="string"/>
                    </all>
                   </complexType>
                  </element>
                 </choice>
                </sequence>
                <attribute name="id" type="int" use="required"/>
               </complexType>
              </element>
             </sequence>
            </complexType>
           </element>

          </schema>


          xml文件:
          <?xml version="1.0" encoding="UTF-8"?>
          <book:books xmlns:book="
             xmlns:xsi="   xsi:noNamespaceSchemaLocation="02.xsd">
           <book:book id="1">
            <book:title>Java in action</book:title>
            <book:content>Java is good</book:content>
            <book:author>Bruce</book:author>
           </book:book>
           <book:book id="2">
            <book:title>SOA in action</book:title>
            <book:content>soa is difficult</book:content>
            <book:authors>
             <book:author>Jike</book:author>
            </book:authors>
           </book:book>
          </book:books>

          schema文件3:
          <?xml version="1.0" encoding="UTF-8"?>
          <schema xmlns="
            targetNamespace="  xmlns:tns="  elementFormDefault="qualified">
            
           <element name="person" type="tns:personType"/>
           
           <complexType name="personType">
            <sequence>
             <element name="name" type="string"/>
             <element name="age" type="tns:ageType"/>
             <element name="email" type="tns:emailType"/>
            </sequence>
            <attribute name="sex" type="tns:sexType"/>
           </complexType>
           
           <simpleType name="emailType">
            <restriction base="string">
             <pattern value="(\w+\.*)*\w+@\w+\.[A-Za-z]{2,6}"/>
             <minLength value="6"/>
             <maxLength value="255"/>
            </restriction>
           </simpleType>
           
           <simpleType name="ageType">
            <restriction base="int">
             <minInclusive value="1"/>
             <maxExclusive value="150"/>
            </restriction>
           </simpleType>
           
           <simpleType name="sexType">
            <restriction base="string">
             <enumeration value="男"/>
             <enumeration value="女"/>
            </restriction>
           </simpleType>
          </schema>

          xml文件:
          <?xml version="1.0" encoding="UTF-8"?>
          <person xmlns="
             xmlns:xsi="   xsi:schemaLocation="  <name>搜索</name>
            <age>149</age>
            <email>sadf@sdf.css</email>
          </person>

          schema文件4:




          posted @ 2013-08-13 09:58 楊軍威 閱讀(200) | 評論 (0)編輯 收藏

          僅列出標題
          共43頁: First 上一頁 12 13 14 15 16 17 18 19 20 下一頁 Last 

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 扬州市| 南投市| 万载县| 姚安县| 资溪县| 内乡县| 会理县| 连云港市| 赤水市| 内丘县| 杭锦旗| 崇明县| 赣榆县| 河曲县| 磴口县| 涞水县| 大厂| 德格县| 英山县| 建湖县| 沙河市| 刚察县| 荆门市| 临汾市| 崇左市| 砀山县| 曲水县| 鄂托克旗| 元阳县| 东乡县| 德昌县| 科尔| 亳州市| 青神县| 紫阳县| 顺平县| 龙游县| 桦南县| 西乌珠穆沁旗| 河东区| 陈巴尔虎旗|