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 杨军威 阅读(390) | 评论 (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 杨军威 阅读(4876) | 评论 (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 杨军威 阅读(462) | 评论 (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 杨军威 阅读(1120) | 评论 (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 杨军威 阅读(37160) | 评论 (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 杨军威 阅读(556) | 评论 (0)编辑 收藏

编写schema引入xml文件中


myschema文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://www.example.org/myschema"
  xmlns:tns="http://www.example.org/myschema"
  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="http://www.example.org/01"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.example.org/01">
 <id>1</id>
 <username>zhangsan</username>
 <born>1989-12-22</born>
</user>

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

posted @ 2013-08-15 17:14 杨军威 阅读(188) | 评论 (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 杨军威 阅读(552) | 评论 (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 = "http://service.soap.org/";
 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("http://java.zttc.edu.cn/webservice",
     "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("//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 杨军威 阅读(1400) | 评论 (0)编辑 收藏

schema的笔记


schema文件:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://www.example.org/01"
  xmlns:tns="http://www.example.org/01"
  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="http://www.example.org/01"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.example.org/01">
 <id>1</id>
 <username>zhangsan</username>
 <born>1989-12-22</born>
</user>

xml文件2:
<?xml version="1.0" encoding="UTF-8"?>
<user xmlns="http://www.example.org/01"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/02"
 xmlns:tns="http://www.example.org/02" elementFormDefault="qualified">

 <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="http://www.example.org/02"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://www.example.org/04"
  xmlns:tns="http://www.example.org/04"
  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="http://www.example.org/04"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.example.org/04" sex="男">
  <name>搜索</name>
  <age>149</age>
  <email>sadf@sdf.css</email>
</person>

schema文件4:




posted @ 2013-08-13 09:58 杨军威 阅读(190) | 评论 (0)编辑 收藏

仅列出标题
共43页: First 上一页 12 13 14 15 16 17 18 19 20 下一页 Last 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜