用户端
1、用户主界面设计
该界面有注册、登陆、查询三个按钮,分别调用各自的方法。界面图如下:
此方法利用Jfram创建,非常简单,在三个按钮的方法处调用方法即可,下面是需要调用方法出的代码:
JButton button = new JButton("注册");
button.setBounds(60, 197, 67, 28);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = textField.getText();
String password = textField_1.getText();
String message = MyMethods.newInstance().register(username, password);//调用Mythods类中的register方法
System.out.println(message);//打印register返回的字符串
}
});
JButton button_1 = new JButton("登陆");
button_1.setBounds(91, 156, 107, 28);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String username = textField.getText();
String password = textField_1.getText();
String message = MyMethods.newInstance().login(username, password);//调用Mythods类中的login方法
System.out.println(message);
}
});
contentPane.add(button_1);
JButton btnNewButton = new JButton("查询");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String message = MyMethods.newInstance().select();//调用Mythods类中的select方法
System.out.println(message);
}
});
btnNewButton.setBounds(156, 197, 67, 28);
contentPane.add(btnNewButton);
}
2、根据MVC编程思想,将三个方法写到一个类中,代码如下
public class MyMethods {
private MyMethods(){
}
private static MyMethods manager;
//下面是设置单例
public static synchronized MyMethods newInstance(){
if(manager == null){
manager = new MyMethods();
}
return manager;
}
/*
下面是注册方法 */
public String register(String username,String password){
String url = "http://localhost:8080/MyServiceTest/MyTest";
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client = builder.build();
HttpPost post = new HttpPost(url);
JSONObject obj = new JSONObject();//利用json封装信息
obj.put("type","注册");
JSONObject data = new JSONObject();
data.put("username", username);//将用户名和密码放进data中
data.put(