Git简单应用

2014-04-01 Git

First time using Git(首次用git)

cd myproject
git init
# add all your files.  Use can use specific filenames or directories instead of '.'
git add .
git commit -a -m 'Initial commit'
git remote add origin ssh:[email protected]/p/doufe-com/code
git push origin master
git branch --set-upstream master origin/master  # so 'git pull' will work later

Existing repository using Git(已经存在库)

cd myproject
git remote add origin ssh:[email protected]/p/doufe-com/code
git push origin master
git branch --set-upstream master origin/master  # so 'git pull' will work later

用Jersey构建RESTful服务6--Jersey+SQLServer+Hibernate4.3

2014-03-26 Java Jersey REST

#一、总体说明

本例运行演示了用Jersey构建RESTful服务中,如何同过Hibernate将数据持久化进SQLServer的过程

#二、环境

  • 1.上文的项目RestDemo
  • 2.SQLServer2005
  • 3.jtds数据库连接驱动:下载地址最新版本,替换掉上文项目中的mysql-connector

#三、配置

1.与上文mysql的配置不同点主要在hibernate.cfg.xml文件; 配置如下:

<?xml version='1.0' encoding='utf-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  
<hibernate-configuration>  
   <session-factory>  
   <!-- Database connection settings -->  
        <property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>  
        <property name="connection.url">jdbc:jtds:sqlserver://192.168.1.10:1433;RestDemo</property>  
        <property name="connection.username">sa</property>  
        <property name="connection.password">aA123456</property>  
        <property name="hibernate.default_schema">RestDemo</property>
        <!-- JDBC connection pool (use the built-in) -->  
        <property name="connection.pool_size">1</property>  
        <!-- SQL dialect -->  
        <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>  
        <!-- Enable Hibernate's automatic session context management -->  
        <property name="current_session_context_class">thread</property>  
        <!-- Disable the second-level cache  -->  
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>  
        <!-- Echo all executed SQL to stdout -->  
        <property name="show_sql">true</property>  
        <!-- Drop and re-create the database schema on startup -->  
        <property name="hbm2ddl.auto">update</property>  
        <mapping resource="com/waylau/rest/bean/User.hbm.xml"/>  
      </session-factory>  
</hibernate-configuration>  

2.修改于mysql不兼容的sql语句com.waylau.rest.dao.impl中的UserDaoImpl:

getUserById修改成如下:

@Override
public User getUserById(String id) {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
	Session s = null;
	Transaction t = null;
	User user = null;
	try{
	 s = sessionFactory.openSession();
	 t = s.beginTransaction();
	 String hql = "from User where userId='"+id+"'";  
	 Query query = s.createQuery(hql);  
	 user = (User) query.uniqueResult(); 
	 t.commit();
	}catch(Exception err){
	t.rollback();
	err.printStackTrace();
	}finally{
	s.close();
	}
	return user;
}

getAllUsers给成如下:

@Override
public List<User> getAllUsers() {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
	Session s = null;
	Transaction t = null;
	List<User> uesrs = null;
	try{
	 s = sessionFactory.openSession();
	 t = s.beginTransaction();
	 String hql = "select * from [RestDemo].dbo.t_user";  
	 Query query = s.createSQLQuery(hql).addEntity(User.class);  
     //query.setCacheable(true); // 设置缓存  
     uesrs = query.list();  
	 t.commit();
	}catch(Exception err){
	t.rollback();
	err.printStackTrace();
	}finally{
	s.close();
	}
	return uesrs;
}

或者如下:

@Override
public List<User> getAllUsers() {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); 
	Session s = null;
	Transaction t = null;
	List<User> uesrs = null;
	try{
	 s = sessionFactory.openSession();
	 t = s.beginTransaction();
	 String hql = " from User";  
	 Query query = s.createQuery(hql);  
     //query.setCacheable(true); // 设置缓存  
     uesrs = query.list();  
	 t.commit();
	}catch(Exception err){
	t.rollback();
	err.printStackTrace();
	}finally{
	s.close();
	}
	return uesrs;
}

#四、问题

##可能会出现如下错误

ERROR: 指定的架构名称 "RestDemo" 不存在,或者您没有使用该名称的权限。
三月 26, 2014 3:38:43 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: insert into RestDemo.T_USER (userName, age, USERID) values (?, ?, ?)
三月 26, 2014 3:38:43 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 208, SQLState: S0002
三月 26, 2014 3:38:43 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: 对象名 'RestDemo.T_USER' 无效。

##解决方案:

将配置文件中的hibernate.default_schema值修改为如下即可:

<property name="hibernate.default_schema">RestDemo.dbo</property>  

或者去掉上面的配置,在“User.hbm.xml”修改如下

<class name="User" table="T_USER" schema="RestDemo.dbo">  

本章源码https://github.com/waylau/RestDemo/tree/master/jersey-demo6-sqlserver-hibernate

https://github.com/waylau/RestDemo/tree/master/jersey-demo6.2-sqlserver-hibernate


用Jersey构建RESTful服务5--Jersey+MySQL5.6+Hibernate4.3

2014-03-23 Java Jersey REST

#一、总体说明

本例运行演示了用Jersey构建RESTful服务中,如何同过Hibernate将数据持久化进MySQL的过程

#二、环境

1.上文的项目RestDemo

2.MySQL5.6下载http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.16-win32.zip

3.Hibernate4.3.4下载http://sourceforge.net/projects/hibernate/files/hibernate4/4.3.4.Final/hibernate-release-4.3.4.Final.zip

4.Java程序连接MySQL的驱动mysql-connector-java-5.1.29-bin.jar下载 http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.29.zip

#三、数据库准备

1.搭建MySQL数据库

2.创建数据库RestDemo ,及数据表t_user,结构如下

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `userId` varchar(50) NOT NULL,
  `userName` varchar(50) NOT NULL,
  `age` varchar(50) NOT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

PS: userId 非自增长类型,需要在业务添加

#四、引入Hibernate

1.解压Hibernate的包,在lib\required文件夹下所有jar引入进项目

2.解压mysql-connector-java-5.1.29.zip,将mysql-connector-java-5.1.29-bin.jar引入进项目

3.在项目的根目录创建hibernate的配置文件hibernate.cfg.xml,内容如下:

<?xml version='1.0' encoding='utf-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  
<hibernate-configuration>  
   <session-factory>  
   <!-- Database connection settings -->  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/RestDemo</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password"></property>  
  
        <!-- JDBC connection pool (use the built-in) -->  
        <property name="connection.pool_size">1</property>  
  
        <!-- SQL dialect -->  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  
        <!-- Enable Hibernate's automatic session context management -->  
        <property name="current_session_context_class">thread</property>  
  
        <!-- Disable the second-level cache  -->  
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>  
   
        <!-- Echo all executed SQL to stdout -->  
        <property name="show_sql">true</property>  
  
        <!-- Drop and re-create the database schema on startup -->  
        <property name="hbm2ddl.auto">update</property>  
  
  
        <mapping resource="com/waylau/rest/bean/User.hbm.xml"/>  
   
    </session-factory>  
</hibernate-configuration>  

4.在项目User.java 的同个目录下,创建该类的映射文件User.hbm.xml

<?xml version="1.0"?>  
<!DOCTYPE hibernate-mapping PUBLIC  
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
  
   
<hibernate-mapping package="com.waylau.rest.bean">  
  
    <class name="User" table="T_USER">  
        <id name="userId" column="USERID"  type="string" >  
            <generator class="assigned"/>  
        </id>  
        <property name="userName" type="string" />  
        <property name="age" type="string" />  
    </class>  
   
</hibernate-mapping>   

5.创建包com.waylau.rest.util,在该包下创建HibernateUtil.java

package com.waylau.rest.util;  
  
import org.hibernate.SessionFactory;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
import org.hibernate.cfg.Configuration;  
/** 
 * Hibernate 初始化配置工具类 
 * @author waylau.com 
 * 2014-3-23 
 */  
public class HibernateUtil {  
     private static Configuration configuration;  
     private static SessionFactory sessionFactory;  
     private static StandardServiceRegistry standardServiceRegistry;  
        static {  
            try {  
             //第一步:读取Hibernate的配置文件  hibernamte.cfg.xml文件  
              configuration = new Configuration().configure("hibernate.cfg.xml");          
             //第二步:创建服务注册构建器对象,通过配置对象中加载所有的配置信息  
              StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();  
              sb.applySettings(configuration.getProperties());  
             //创建注册服务  
              standardServiceRegistry = sb.build();    
            //第三步:创建会话工厂  
              sessionFactory = configuration.buildSessionFactory(standardServiceRegistry);     
            } catch (Throwable ex) {  
                // Make sure you log the exception, as it might be swallowed  
                System.err.println("Initial SessionFactory creation failed." + ex);  
                throw new ExceptionInInitializerError(ex);  
            }  
        }  
  
        public static SessionFactory getSessionFactory() {  
            return sessionFactory;  
        }  
}  

6.在项目中建com.waylau.rest.dao包,在该包下建立User操作的接口UserDao.java

package com.waylau.rest.dao;  
  
import java.util.List;  
  
import com.waylau.rest.bean.User;  
   
  
/** 
 * User Dao 接口 
 * @author waylau.com 
 * 2014-3-18 
 */  
public interface UserDao {  
      
    public User getUserById(String id);  
  
    public boolean deleteUserById(String id);  
  
    public boolean createUser(User user);  
  
    public boolean updateUser(User user);  
  
    public List<User> getAllUsers();  
}  

7.在项目中建com.waylau.rest.dao.impl包,在该包下建立User操作接口的实现UserDaoImpl.java

package com.waylau.rest.dao.impl;  
  
import java.util.List;  
  
import org.hibernate.Query;  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
  
import com.waylau.rest.bean.User;  
import com.waylau.rest.dao.UserDao;  
import com.waylau.rest.util.HibernateUtil;  
/** 
 * 用户DAO实现 
 * @author waylau.com 
 * 2014-3-23 
 */  
public class UserDaoImpl implements UserDao {  
  
    @Override  
    public User getUserById(String id) {  
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
        Session s = null;  
        Transaction t = null;  
        User user = null;  
        try{  
         s = sessionFactory.openSession();  
         t = s.beginTransaction();  
         String hql = "from User where userId="+id;    
         Query query = s.createQuery(hql);    
         user = (User) query.uniqueResult();   
         t.commit();  
        }catch(Exception err){  
        t.rollback();  
        err.printStackTrace();  
        }finally{  
        s.close();  
        }  
        return user;  
    }  
  
    @Override  
    public boolean deleteUserById(String id) {  
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
        Session s = null;  
        Transaction t = null;  
        boolean flag = false;  
        try{  
         s = sessionFactory.openSession();  
         t = s.beginTransaction();  
         User user = new User();    
         user.setUserId(id);  
         s.delete(user);  
         t.commit();  
         flag = true;  
        }catch(Exception err){  
        t.rollback();  
        err.printStackTrace();  
        }finally{  
        s.close();  
        }  
        return flag;  
    }  
  
    @Override  
    public boolean createUser(User user) {  
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
        Session s = null;  
        Transaction t = null;  
        boolean flag = false;  
        try{  
         s = sessionFactory.openSession();  
         t = s.beginTransaction();  
         s.save(user);  
         t.commit();  
         flag = true;  
        }catch(Exception err){  
        t.rollback();  
        err.printStackTrace();  
        }finally{  
        s.close();  
        }  
        return flag;  
    }  
  
    @Override  
    public boolean updateUser(User user) {  
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
        Session s = null;  
        Transaction t = null;  
        boolean flag = false;  
        try{  
         s = sessionFactory.openSession();  
         t = s.beginTransaction();  
         s.update(user);  
         t.commit();  
         flag = true;  
        }catch(Exception err){  
        t.rollback();  
        err.printStackTrace();  
        }finally{  
        s.close();  
        }  
        return flag;  
    }  
  
    @Override  
    public List<User> getAllUsers() {  
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();   
        Session s = null;  
        Transaction t = null;  
        List<User> uesrs = null;  
        try{  
         s = sessionFactory.openSession();  
         t = s.beginTransaction();  
         String hql = "select * from t_user";    
         Query query = s.createSQLQuery(hql).addEntity(User.class);    
         query.setCacheable(true); // 设置缓存    
         uesrs = query.list();    
         t.commit();  
        }catch(Exception err){  
        t.rollback();  
        err.printStackTrace();  
        }finally{  
        s.close();  
        }  
        return uesrs;  
    }  
  
}  

8.修改项目中 com.waylau.rest.resources包下的UserResource.java,使之前在内存中模拟CURD转为在数据库中实现

package com.waylau.rest.resources;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import javax.ws.rs.Path;  
import javax.ws.rs.Produces;  
import javax.ws.rs.Consumes;  
import javax.ws.rs.PathParam;  
import javax.ws.rs.core.MediaType;  
import javax.ws.rs.DELETE;  
import javax.ws.rs.GET;  
import javax.ws.rs.POST;  
import javax.ws.rs.PUT;  
  
import com.waylau.rest.bean.User;  
import com.waylau.rest.dao.impl.UserDaoImpl;  
  
/** 
 * 用户资源 
 * @author waylau.com 
 * 2014-3-19 
 */  
@Path("/users")  
public class UserResource {  
    private UserDaoImpl userDaoImpl = new UserDaoImpl();  
    /** 
     * 增加 
     * @param user 
     */  
    @POST  
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
    public void createUser(User user)  
    {  
        userDaoImpl.createUser(user);  
    }  
      
    /** 
     * 删除 
     * @param id 
     */  
    @DELETE  
    @Path("{id}")  
    public void deleteUser(@PathParam("id")String id){  
        userDaoImpl.deleteUserById(id);  
    }  
      
    /** 
     * 修改 
     * @param user 
     */  
    @PUT  
    @Consumes(MediaType.APPLICATION_XML)  
    public void updateUser(User user){  
        userDaoImpl.updateUser(user);  
    }  
   
    /** 
     * 根据id查询 
     * @param id 
     * @return 
     */  
    @GET  
    @Path("{id}")  
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
    public User getUserById(@PathParam("id") String id){  
        User u = userDaoImpl.getUserById(id);  
        return u;  
    }  
     
    /** 
     * 查询所有 
     * @return 
     */  
    @GET  
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
    public List<User> getAllUsers(){       
        List<User> users = new ArrayList<User>();     
        users = userDaoImpl.getAllUsers();  
        return users;  
    }  
      
      
}  

#五、运行 1.将服务端运行后

2.运行UserClient客户端,可以看到数据库已经实现增删改查

完整项目架构如下:

本章源码https://github.com/waylau/RestDemo/tree/master/jersey-demo5-mysql-hibernate


用Jersey构建RESTful服务4--通过jersey-client客户端调用Jersey的Web服务模拟CURD

2014-03-19 Java Jersey REST

#一、总体说明

通过jersey-client接口,创建客户端程序,来调用Jersey实现的RESTful服务,实现增、删、改、查等操作。 服务端主要是通过内存的方式,来模拟用户的增加、删除、修改、查询等操作。

#二、创建服务端

1.在上文项目中, 在“com.waylau.rest.resources.UserResource“中修改代码, 首先创建一个HashMap,用来保存添加的用户

private static Map<String,User> userMap  = new HashMap<String,User>();  

2.创建增、删、改、查 用户资源等操作


    /** 
     * 增加 
     * @param user 
     */  
    @POST  
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
    public void createStudent(User user)  
    {  
        userMap.put(user.getUserId(), user );  
    }  
      
    /** 
     * 删除 
     * @param id 
     */  
    @DELETE  
    @Path("{id}")  
    public void deleteStudent(@PathParam("id")String id){  
        userMap.remove(id);  
    }  
      
    /** 
     * 修改 
     * @param user 
     */  
    @PUT  
    @Consumes(MediaType.APPLICATION_XML)  
    public void updateStudent(User user){  
        userMap.put(user.getUserId(), user );  
    }  
   
    /** 
     * 根据id查询 
     * @param id 
     * @return 
     */  
    @GET  
    @Path("{id}")  
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
    public User getUserById(@PathParam("id") String id){  
        User u = userMap.get(id);  
        return u;  
    }  
     
    /** 
     * 查询所有 
     * @return 
     */  
    @GET  
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})  
    public List<User> getAllUsers(){       
        List<User> users = new ArrayList<User>();     
        users.addAll( userMap.values() );    
        return users;  
    }  

#三、创建客户端程序

1.创建包“com.waylau.rest.client”,在包下建一个UserClient.java,代码如下:


	package com.waylau.rest.client;  
	  
	import javax.ws.rs.client.Client;  
	import javax.ws.rs.client.ClientBuilder;  
	import javax.ws.rs.client.Entity;  
	import javax.ws.rs.client.WebTarget;  
	import javax.ws.rs.core.MediaType;  
	import javax.ws.rs.core.Response;  
	  
	import org.codehaus.jackson.jaxrs.JacksonJsonProvider;  
	  
	import com.waylau.rest.bean.User;  
	  
	   
	/** 
	 * 用户客户端,用来测试资源 
	 * @author waylau.com 
	 * 2014-3-18 
	 */  
	public class UserClient {  
	  
	    private static String serverUri = "http://localhost:8089/RestDemo/rest";  
	    /** 
	     * @param args 
	     */  
	    public static void main(String[] args) {  
	        addUser();  
	        getAllUsers();  
	        updateUser();  
	        getUserById();  
	        getAllUsers();  
	        delUser();  
	        getAllUsers();  
	  
	    }  
	    /** 
	     * 添加用户 
	     */  
	     private static void addUser() {  
	         System.out.println("****增加用户addUser****");  
	         User user = new User("006","Susan","21");    
	         Client client = ClientBuilder.newClient();  
	         WebTarget target = client.target(serverUri + "/users");  
	         Response response = target.request().buildPost(Entity.entity(user, MediaType.APPLICATION_XML)).invoke();  
	         response.close();  
	    }  
	       
	    /** 
	     * 删除用户 
	     */  
	     private static void delUser() {  
	         System.out.println("****删除用户****");  
	         Client client = ClientBuilder.newClient();  
	         WebTarget target = client.target(serverUri + "/users/006");  
	         Response response = target.request().delete();  
	         response.close();  
	    }  
	       
	       
	    /** 
	     * 修改用户 
	     */  
	     private static void updateUser() {  
	         System.out.println("****修改用户updateUser****");  
	         User user = new User("006","Susan","33");    
	         Client client = ClientBuilder.newClient();  
	         WebTarget target = client.target(serverUri + "/users");  
	         Response response = target.request().buildPut( Entity.entity(user, MediaType.APPLICATION_XML)).invoke();  
	         response.close();  
	    }  
	    /** 
	     * 根据id查询用户 
	     */  
	     private static void getUserById() {  
	         System.out.println("****根据id查询用户****");  
	         Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);// 注册json 支持  
	         WebTarget target = client.target(serverUri + "/users/006");  
	         Response response = target.request().get();  
	         User user = response.readEntity(User.class);  
	         System.out.println(user.getUserId() + user.getUserName()  +  user.getAge());  
	         response.close();  
	    }  
	    /** 
	     * 查询所有用户 
	     */  
	     private static void getAllUsers() {  
	         System.out.println("****查询所有getAllUsers****");  
	           
	         Client client = ClientBuilder.newClient();  
	  
	         WebTarget target = client.target(serverUri + "/users");  
	         Response response = target.request().get();  
	 		 String value = response.readEntity(String.class);  
	    	 System.out.println(value);  
			 response.close();  //关闭连接  
	     }  
	       
	}  

#四、运行 启动服务端项目,运行客户端程序UserClient,控制台输出如下

****增加用户addUser****  
****查询所有getAllUsers****  
[{"userId":"006","userName":"Susan","age":"21"}]  
****修改用户updateUser****  
****根据id查询用户****  
006Susan33  
****查询所有getAllUsers****  
[{"userId":"006","userName":"Susan","age":"33"}]  
****删除用户****  
****查询所有getAllUsers****  
[]  

#五、总结 1.客户端如果需要进行JSON转换,需要进行JSON注册

Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);  

2.WebTarget 指明了要请求的资源的地址

3.target.request(). 后面跟的是请求的方法:POST,GET,PUT或DELETE

本章源码https://github.com/waylau/RestDemo/tree/master/jersey-demo4-client-curd


用Jersey构建RESTful服务3--JAVA对象转成JSON输出

2014-03-17 Java Jersey REST

#一、 总体说明

XML和JSON 是最为常用的数据交换格式。本例子演示如何将java对象,转成JSON输出。

#二、流程

  • 1.在上文项目中, 在“com.waylau.rest.resources.UserResource“中增加代码,代码如下:
	@GET    
	@Path("/getUserJson")    
	@Produces(MediaType.APPLICATION_JSON)    
	public User getUserJson() {    
	 User user  = new User();    
	 user.setAge("27");    
	 user.setUserId("005");    
	 user.setUserName("Fmand");    
	 return user;    
	}   

MediaType.APPLICATION_JSON 说明输出的是JSON格式

	org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class com.waylau.rest.bean.User, genericType=class com.waylau.rest.bean.User.  
	    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)  
	    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)  
	    at org.glassfish.jersey.filter.LoggingFilter.aroundWriteTo(LoggingFilter.java:293)  
	    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)  
	    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:103)  
	    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)  
	    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:88)  
	    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)  
	    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1154)  
	    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:571)  
	    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:378)  
	    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:368)  
	    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:262)  

此时,需要获取json转换包的支持 。 可以由多种方式实现:MOXy、JSON-P、Jackson、Jettison等,本例为Jackson。

    1. jackson-all-1.9.11.jar 下载地址http://wiki.fasterxml.com/JacksonDownload
    1. 项目中引入jackson-all-1.9.11.jar
  • 5.在“com.waylau.rest”目录下创建RestApplication.java
package com.waylau.rest;  
  
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;  
import org.glassfish.jersey.filter.LoggingFilter;  
import org.glassfish.jersey.server.ResourceConfig;  
   
/** 
 * 应用 
 * @author waylau.com 
 * 2014-3-18 
 */  
public class RestApplication extends ResourceConfig {  
    public RestApplication() {  
   
     //服务类所在的包路径  
     packages("com.waylau.rest.resources");  
     //注册JSON转换器  
     register(JacksonJsonProvider.class);  
   
    }  
}  
  • 6.修改web.xml,初始化从RestApplicaton进入应用,如下:
<servlet>    
     <servlet-name>Way REST Service</servlet-name>  
     <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  
      <init-param>  
           <param-name>javax.ws.rs.Application</param-name>  
           <param-value>com.waylau.rest.RestApplication</param-value>  
       </init-param>  
       
    <load-on-startup>1</load-on-startup>  
  </servlet>  
    
  <servlet-mapping>  
    <servlet-name>Way REST Service</servlet-name>  
    <url-pattern>/rest/*</url-pattern>  
  </servlet-mapping>  

本章源码https://github.com/waylau/RestDemo/tree/master/jersey-demo3-json


用Jersey构建RESTful服务2--JAVA对象转成XML输出

2014-03-17 Java Jersey REST

##一、 总体说明 XML和JSON 是最为常用的数据交换格式。本例子演示如何将java对象,转成XML输出。 ##二、流程 * 1.在上文的例子中,创建一个包“com.waylau.rest.bean” * 2.在该包下创建一个JAVA类”User”

	package com.waylau.rest.bean;  
	import javax.xml.bind.annotation.XmlRootElement;  
	/* *
	 * 用户 bean 
	 * @author waylau.com 
	 * 2014-3-17 
	 */  
	@XmlRootElement  
	public class User {  
	      
	    private String userId;  
	    private String userName;  
	    private String age;  
	      
	    public User() {};  
	      
	    public User(String userId, String userName, String age) {  
	        this.userId = userId;  
	        this.userName = userName;  
	        this.age = age;  
	    }  
	    public String getUserId() {  
	        return userId;  
	    }  
	    public void setUserId(String userId) {  
	        this.userId = userId;  
	    }  
	    public String getUserName() {  
	        return userName;  
	    }  
	    public void setUserName(String userName) {  
	        this.userName = userName;  
	    }  
	    public String getAge() {  
	        return age;  
	    }  
	    public void setAge(String age) {  
	        this.age = age;  
	    }  
	}  

注意:[email protected],在将该类转化成XML时,说明这个是XML的根节点。

  • 3.在“com.waylau.rest.resources”中,增加资源“UserResource“,代码如下:
	package com.waylau.rest.resources;  
	  
	import java.util.ArrayList;  
	import java.util.HashMap;  
	import java.util.List;  
	import java.util.Map;  
	  
	import javax.ws.rs.Path;  
	import javax.ws.rs.Produces;  
	import javax.ws.rs.PathParam;  
	import javax.ws.rs.core.MediaType;  
	import javax.ws.rs.DELETE;  
	import javax.ws.rs.GET;  
	import javax.ws.rs.POST;  
	import javax.ws.rs.PUT;  
	  
	import com.waylau.rest.bean.User;  
	  
	@Path("/users")  
	public class UserResource {  
	    private static Map<String,User> userMap = new HashMap<String,User>();//存储用户  
	     /** 
	     * 查询所有 
	     * @return 
	     */  
	    @GET  
	    @Produces(MediaType.APPLICATION_XML)  
	    public List<User> getAllUsers(){       
	        List<User> users = new ArrayList<User>();  
	        User u1 = new User("001","WayLau","26");  
	        User u2 = new User("002","King","23");  
	        User u3 = new User("003","Susan","21");  
	          
	        userMap.put(u1.getUserId(), u1);  
	        userMap.put(u2.getUserId(), u2);  
	        userMap.put(u3.getUserId(), u3);  
	          
	        users.addAll( userMap.values() );  
	        return users;  
	    }  
	      
	    @GET  
	    @Path("/getUserXml")  
	    @Produces(MediaType.APPLICATION_XML)  
	    public User getUserXml() {  
	     User user  = new User();  
	     user.setAge("21");  
	     user.setUserId("004");  
	     user.setUserName("Amand");  
	     return user;  
	    }  
	}  

其中MediaType.APPLICATION_XML 说明了是以XML形式输出

在浏览器输入http://localhost:8089/RestDemo/rest/users/getUserXml,输出单个对象 在浏览器输入 http://localhost:8089/RestDemo/rest/users 输出对象的集合

本章源码https://github.com/waylau/RestDemo/tree/master/jersey-demo2-xml


用Jersey构建RESTful服务1--HelloWorld

2014-03-17 Java Jersey REST

#一、环境 * 1.Eclipse Juno R2 * 2.Tomcat 7 * 3.Jersey 2.x(最新2.11版本测试通过) 下载地址( https://jersey.java.net/download.html

#二、流程 * 1.Eclipse 中创建一个 Dynamic Web Project ,本例为“RestDemo” * 2.按个各人习惯建好包,本例为“com.waylau.rest.resources” * 3.解压jaxrs-ri-2.7,将api、ext、lib文件夹下的jar包都放到项目的lib下; 项目引入jar包 * 4.在resources包下建一个class“HelloResource”


	package com.waylau.rest.resources; 
	import javax.ws.rs.GET; 
	import javax.ws.rs.Path; 
	import javax.ws.rs.Produces; 
	import javax.ws.rs.PathParam; 
	import javax.ws.rs.core.MediaType; 
	@Path("/hello") 
	public class HelloResource { 
		@GET @Produces(MediaType.TEXT_PLAIN) 
		public String sayHello() 
		{ 
			return "Hello World!" ; 
		}
		
		@GET @Path("/{param}") 
		@Produces("text/plain;charset=UTF-8") 
		public String sayHelloToUTF8(@PathParam("param") String username) 
		{ 
			return "Hello " + username; 
		}
		
	}
  • 5.修改web.xml,添加基于Servlet-的部署
<servlet> 
	<servlet-name>Way REST Service</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
	<init-param> 
	<param-name>jersey.config.server.provider.packages</param-name> 
	<param-value>com.waylau.rest.resources</param-value> </init-param> 
	<load-on-startup>1</load-on-startup> 
</servlet>

<servlet-mapping> 
	<servlet-name>Way REST Service</servlet-name> 
	<url-pattern>/rest/*</url-pattern> 
</servlet-mapping>

http://localhost:8089/RestDemo/rest/hello/Way你好吗,输出Hello Way你好吗

参考:https://jersey.java.net/documentation/latest/user-guide.html

本章源码https://github.com/waylau/RestDemo/tree/master/jersey-demo1-helloworld


Flex4 Label文本换行

2014-03-12 Flex

图标中的文本如果太长就显示不全了。 图片 查API , Label继承了TextBase,而 TextBase有maxDisplayedLines属性,表述如下: 确定是否截断文本以及在何处截断文本的整数。

截断文本意味着使用截断指示符(如 "...")替换超额文本。截断指示符与区域设置相关;它是由 "core" 资源包中的 "truncationIndicator" 资源指定的。
如果值为 0,则不会发生截断。相反,如果文本不在组件的界限内,则将只是剪辑文本。
如果值为正整数,则会根据需要截断文本以将行数减少至此整数。
如果值为 -1,则会截断该文本以显示将完全放在组件的高度内的行。
仅当 lineBreak 样式为 "toFit" 时,才执行截断;如果 lineBreak 为 "explicit",则会忽略此属性的值。
默认值为 0。
将 maxDisplayedLines 设为2,解决 图片