1. 程式人生 > >MySql+webService cxf+json 簡單框架

MySql+webService cxf+json 簡單框架

這個Demo是非常簡單的一個框架。如果您需要開發的話完全可以按照這個大框架的基礎上實現您的各種方法。新手可以看一下。本demo的程式碼書寫規範完全是本人自己的習慣。服務端是:webService+cxf+Json, 客戶端是android。

伺服器端程式碼:

包結構圖:

包結構

1.1javaBean的部分沒有什麼可說的,上程式碼:

CommandBean

public class CommandBean {

	private String status;//0 正確     -1:此使用者不存在,1:使用者存在, -2,資料插入失敗
	private String errmsg;//錯誤資訊

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getErrmsg() {
		return errmsg;
	}

	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}

}


UserBean

public class UserBean {

	private String name;
	private Integer age;
	private String account;
	private String password;

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public UserBean(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	public UserBean() {
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "UserBean [name=" + name + ", age=" + age + ", account="
				+ account + ", password=" + password + "]";
	}

}

1.2 cxf介面:

@WebService
public interface ILoginService {

	String login(@WebParam(name = "username") String username,
			@WebParam(name = "password") String password);
}

1.3 cxf實現類

@WebService(endpointInterface = "com.cxf.service.ILoginService", serviceName = "LoginServiceService")
public class LoginService implements ILoginService {

	@Override
	public String login(String username, String password) {
		LoginHelper loginHelper = new LoginHelper();
		CommandBean commandBean = loginHelper.onLogin(username, password);
		String jsonStr = JsonOperator.toJson(commandBean);
		return jsonStr;
	}

}

2.1.1資料庫介面1

public interface DBService {

	void onCloseDB();//關閉資料庫
}

2.1.2資料庫介面2

public interface LoginService {
	/**
	 * 登陸
	 * 
	 * @param account
	 *            賬號
	 * @param password
	 *            密碼
	 * @return
	 */
	CommandBean onLogin(String account, String password);

	/**
	 * 註冊
	 * 
	 * @param UserBean
	 *            使用者實體
	 * @return
	 */
	CommandBean onRegisterAccount(UserBean user);
}


2.2.1資料庫介面實現類

public class DBHelper implements DBService {

	private final static String URL = "jdbc:mysql://localhost:3306/workmate?user=root&password=admin";
	private Statement stmt;
	private Connection conn;

	public DBHelper() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(URL);
			stmt = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onCloseDB() {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO: handle exception
			}
		}
	}

	public Statement getStatement() {
		return stmt;
	}

	public Connection getConnection() {
		return conn;
	}

}


2.2.2 資料庫介面實現類

public class LoginHelper extends DBHelper implements LoginService {

	private Connection conn;
	private Statement stmt;

	public LoginHelper() {
		conn = getConnection();
		stmt = getStatement();
	}

	@Override
	public CommandBean onLogin(String account, String password) {
		CommandBean command = new CommandBean();
		PreparedStatement ps;
		String sql = "select * from wm_t_user where account=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, account);
			ResultSet set = ps.executeQuery();
			if (set.next()) {// 使用者名稱正確
				String pwd = set.getString("password");
				if (pwd.equals(password)) {// 密碼正確
					command.setStatus("0");
				} else {// 密碼不正確
					command.setStatus("-2");// 密碼錯誤
					command.setErrmsg("密碼不正確");
				}
			} else {// 不存在此使用者
				command.setStatus("-1");
				command.setErrmsg("此使用者不存在");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return command;
	}

	@Override
	public CommandBean onRegisterAccount(UserBean user) {
		CommandBean command = new CommandBean();
		PreparedStatement ps;
		String sql = "select * from wm_t_user where account=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getAccount());
			ResultSet set = ps.executeQuery();
			if (set.next()) {// 使用者存在
				command.setStatus("1");
				command.setErrmsg("此使用者存在");
			} else {// 不存在此使用者
				if (insertUser(user) > 0) {// 插入成功
					command.setStatus("0");
				} else {// 插入失敗
					command.setStatus("-2");
					command.setErrmsg("資料庫插入失敗");
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return command;
	}

	private int insertUser(UserBean user) {
		String sql = "insert into wm_t_user(account,password,username,age)values(?,?,?,?)";
		PreparedStatement ps;
		int rowNo = -1;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getAccount());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getName());
			ps.setInt(4, user.getAge());
			rowNo = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rowNo;
	}

	public static void main(String[] args) {
		LoginHelper db = new LoginHelper();
		UserBean user = new UserBean();
		user.setAccount("xxl6");
		user.setAge(28);
		user.setName("xxl");
		user.setPassword("0000");
		CommandBean commandBean = db.onRegisterAccount(user);
		// if(!commandBean.getStatus().equals("0")){
		// System.out.println(commandBean.getErrmsg());
		// }
		// System.out.println(commandBean.getStatus());
	}

}

3.json解析幫助類
/**
 * Json與javaBean之間的轉換工具類
 * 
 */
public class JsonOperator {

	/**
	 * 將java物件轉換成json字串
	 */
	public static <T> T json2Bean(String jsonString, Class<T> cls) {
		T t = null;
		try {
			Gson gson = new Gson();
			t = gson.fromJson(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 將物件轉換成json資料
	 * 
	 * @param o
	 * @return
	 */
	public static <T> String toJson(Object o) {
		Gson gson = new Gson();
		String jsonStr = gson.toJson(o);
		return jsonStr;
	}

	/**
	 * 將json資料轉換成List列表返回
	 * 
	 * @param jsonString
	 * @param type
	 * @return
	 */
	public static <T> List<T> json2List(String jsonString, Type type) {
		List<T> list = new ArrayList<T>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, type);
		} catch (Exception e) {
		}
		return list;
	}

	// public static void main(String[] args) {
	// String jsonStr = "[{\"name\":\"ice\",\"age\":20}]";
	// List<UserBean> list = json2List(jsonStr,
	// new TypeToken<List<UserBean>>() {
	// }.getType());
	// for (UserBean user : list)
	// System.out.println(user.getAge() + "");
	// }
}

XML的解析本案例中沒有實現。 服務端結束,在main中右鍵-》run as-》java application
到此服務端結束。

下面配置Android端。

下表面看一下包結構。

1javaBean是完全從服務單copy下來的。所以不列程式碼。

2主Activity。

public class MainActivity extends Activity {

	private String CLASS_NAME = getClass().getName();
	private SoapService service;
	private EditText etPwd, etAccount;
	private Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initWindow();
		initHandler();
	}

	private void initHandler() {
		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT)
							.show();
					break;
				default:
					Toast.makeText(MainActivity.this, msg.obj.toString(),
							Toast.LENGTH_SHORT).show();
					break;
				}
			}

		};
	}

	private void initWindow() {
		service = new SoapService();
		service.setNamespace("http://service.cxf.com/");

		etPwd = (EditText) findViewById(R.id.et_pwd);
		etAccount = (EditText) findViewById(R.id.et_account);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void login(View v) {
		service.setMethodName("login");
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("username", etAccount.getText().toString().trim());
		paramsMap.put("password", etPwd.getText().toString().trim());
		service.setParams(paramsMap);
		new Thread(new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();
				msg.what = 0;
				try {
					String resultJson = service.invoke();
					CommandBean command = JsonOperator.json2Bean(resultJson,
							CommandBean.class);
					msg.what = new Integer(command.getStatus());
					msg.obj = command.getErrmsg();
					mHandler.sendMessage(msg);
				} catch (XmlPullParserException e) {
					e.printStackTrace();
					msg.what = -1;
				} catch (IOException e) {
					e.printStackTrace();
					msg.what = -2;
				}
			}
		}).start();

	}
}

3.json解析也是完全從服務端COPY過來。

4.與伺服器通訊類程式碼

/**
 * 與伺服器通訊所用
 * 
 * @author Administrator
 * 
 */
public class SoapService {

	private final static String url = "http://192.168.1.40:8989/wm/login?wsdl";
	private String namespace = "http://service.cxf.com/";
	private String methodName = "";
	private Class<?> cls;
	private HashMap<String, String> paramsMap;

	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public String invoke() throws XmlPullParserException, IOException {
		HttpTransportSE httpTransportSE = new HttpTransportSE(url);
		httpTransportSE.debug = true;

		SoapObject requestObject = new SoapObject(namespace, methodName);
		// 欄位名稱和get欄位名稱
		Iterator it = paramsMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String paramName = entry.getKey().toString();
			String value = entry.getValue().toString();
			requestObject.addProperty(paramName, value);
		}
		SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		soapEnvelope.setOutputSoapObject(requestObject);
		soapEnvelope.dotNet = false;
		String resultJsonStr = "";
		httpTransportSE.call(null, soapEnvelope);
		if (soapEnvelope.getResponse() != null) {
			SoapObject result = (SoapObject) soapEnvelope.bodyIn;
			resultJsonStr = result.getProperty("return").toString();
		}
		return resultJsonStr;
	}

	public void setParams(String className) {
		// 獲取類,取得屬性值
		try {
			cls = Class.forName(className);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setParams(HashMap<String, String> paramsMap) {
		this.paramsMap = paramsMap;
	}

}

到此客戶端也新增完成。  不要忘記在AndroidManifest.xml中新增<uses-permission android:name="android.permission.INTERNET"/>許可權。 在Android執行的圖示:

 1登陸成功。


2.使用者不存在


3.密碼錯誤。


資料庫截圖


原始碼下載。

服務端下載