登錄、註冊、查詢(java項目中)
package com.java.http;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("登錄");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String myHttpClient=MyHttpClient.newInstance().login(textField.getText(), textField_1.getText());
System.out.println(myHttpClient);
}
});
btnNewButton.setBounds(157, 171, 93, 23);
contentPane.add(btnNewButton);
JLabel label = new JLabel("用戶名");
label.setBounds(78, 61, 54, 15);
contentPane.add(label);
JLabel label_1 = new JLabel("密碼");
label_1.setBounds(78, 119, 54, 15);
contentPane.add(label_1);
textField = new JTextField();
textField.setBounds(166, 58, 84, 28);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(166, 116, 84, 28);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnNewButton_1 = new JButton("註冊");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
btnNewButton_1.setBounds(151, 202, 65, 23);
contentPane.add(btnNewButton_1);
JButton button = new JButton("查詢");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String myHttpClient=MyHttpClient.newInstance().select();
System.out.println(myHttpClient);
}
});
button.setBounds(285, 171, 93, 23);
contentPane.add(button);
}
}
package com.java.http;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Register extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Create the frame.
*/
public Register() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("註冊");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String myHttpClient=MyHttpClient.newInstance().register(textField.getText(), textField_1.getText());
System.out.println(myHttpClient);
}
});
btnNewButton.setBounds(140, 136, 113, 47);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("用戶名");
lblNewLabel.setBounds(51, 32, 54, 15);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("密碼");
lblNewLabel_1.setBounds(51, 82, 54, 15);
contentPane.add(lblNewLabel_1);
textField = new JTextField();
textField.setBounds(150, 27, 87, 26);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(150, 73, 87, 33);
contentPane.add(textField_1);
textField_1.setColumns(10);
}
}
HttpClient(定義JSON格式的註冊、登錄、查詢)
package com.java.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import net.sf.json.JSONObject;
public class MyHttpClient {
private static MyHttpClient myHttpClient;
private MyHttpClient(){
}
public static synchronized MyHttpClient newInstance(){
if(myHttpClient==null){
myHttpClient=new MyHttpClient();
}
return myHttpClient;
}
/**
* 註冊JSON格式
* @param userName
* @param password
* @return
*/
public String register(String userName,String password){
String urlString="http://localhost:8080/JavaEE/Servlet";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost post=new HttpPost(urlString);
JSONObject obj=new JSONObject();
obj.put("userName", userName);
obj.put("password", password);
JSONObject object=new JSONObject();
object.put("type", "Register");
object.put("data", obj);
NameValuePair pair=new BasicNameValuePair("json",object.toString());
ArrayList<NameValuePair> list=new ArrayList<>();
list.add(pair);
try {
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpResponse response=client.execute(post);
int code=response.getStatusLine().getStatusCode();
if(code==HttpURLConnection.HTTP_OK){
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer buffer=new StringBuffer();
String line=br.readLine();
while(line!=null){
buffer.append(line);
System.out.println(line);
line=br.readLine();
}
return buffer.toString();
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
/**
*
* @param username
* @param password
* @return
*/
public String login(String userName,String password){
String url="http://localhost:8080/JavaEE/Servlet";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost post=new HttpPost(url);
JSONObject object=new JSONObject();
object.put("type", "Login");
JSONObject obj=new JSONObject();
obj.put("userName", userName);
obj.put("password", password);
object.put("data", obj);
NameValuePair pair1=new BasicNameValuePair("json", object.toString());
ArrayList<NameValuePair> params=new ArrayList<>();
params.add(pair1);
try {
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpResponse response=client.execute(post);
int code=response.getStatusLine().getStatusCode();
if(code==200){
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
StringBuffer buffer=new StringBuffer();
while(line!=null){
buffer.append(line);
System.out.println(line);
line=br.readLine();
}
return buffer.toString();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @return
*/
public String select(){
String url="http://localhost:8080/JavaEE/Servlet";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost post=new HttpPost(url);
JSONObject obj=new JSONObject();
obj.put("type", "Select");
NameValuePair pair1=new BasicNameValuePair("json", obj.toString());
ArrayList<NameValuePair> params=new ArrayList<>();
params.add(pair1);
try {
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpResponse response=client.execute(post);
int code=response.getStatusLine().getStatusCode();
if(code==200){
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
StringBuffer buffer=new StringBuffer();
while(line!=null){
buffer.append(line);
System.out.println(line);
line=br.readLine();
}
return buffer.toString();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Encoding(JavaEE項目中)
package com.java.json;
import java.io.UnsupportedEncodingException;
public class Encoding {
public static String doEncoing(String string) {
try {
if(string ==null){
return null;
}
byte[] array=string.getBytes("ISO-8859-1");
string=new String(array,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return string;
}
}
SQLOperate
package com.java.json;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class SQLOperate {
public static final int SUCESS=0;
public static final int ERRO=1;
private static SQLOperate operate;
private SQLOperate(){
}
/**
*
* @return
*/
public static SQLOperate newInstance(){
if(operate==null){
operate=new SQLOperate();
}
return operate;
}
/**
* 註冊方法
* @param userName
* @param password
* @return
*/
public static String register(String userName,String password){
Connection con=SQLManager.newInstance().getConnection();
JSONObject object=new JSONObject();
try {
PreparedStatement statement=con.prepareStatement("select * from user where user_name=?");
statement.setString(1, userName);
statement.execute();
ResultSet set=statement.executeQuery();
set.last();
int num=set.getRow();
if(num==1){
object.put("code", 1);
object.put("message", "該用戶已存在");
}else if(num==0){
PreparedStatement statement2=con.prepareStatement("insert into user(user_name,password)values(?,?)");
statement2.setString(1, userName);
statement2.setString(2, password);
statement2.execute();
object.put("code", 0);
object.put("message", "註冊成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
return object.toString();
}
/**
* 登錄方法
* @param userName
* @param password
* @return
*/
public static String login(String userName,String password){
Connection con=SQLManager.newInstance().getConnection();
JSONObject object=new JSONObject();
try {
PreparedStatement state=con.prepareStatement("select * from user where user_name=?");
state.setString(1, userName);
ResultSet set=state.executeQuery();
set.last();
int num=set.getRow();
System.out.println(num);
if(num==0){
object.put("code", 1);
object.put("message", "用戶名錯誤");
return object.toString();
}
PreparedStatement state2=con.prepareStatement("select * from user where user_name=? and password=?");
state2.setString(1, userName);
state2.setString(2, password);
ResultSet set2=state2.executeQuery();
set2.last();
int num2=set2.getRow();
if(num2>0){
object.put("code", 0);
object.put("message", "登錄成功");
return object.toString();
}else{
object.put("code", 1);
object.put("message", "登錄失敗");
return object.toString();
}
} catch (SQLException e) {
e.printStackTrace();
}
return object.toString();
}
/**
* 查詢方法
* @return
*/
public String select(){
JSONObject object=new JSONObject();
Connection con=SQLManager.newInstance().getConnection();
try {
PreparedStatement state=con.prepareStatement("select * from user");
ResultSet set=state.executeQuery();
set.first();
JSONArray array=new JSONArray();
while(!set.isAfterLast()){
JSONObject item=new JSONObject();
item.put("password",set.getString("password"));
item.put("userName", set.getString("user_name"));
array.add(item);
set.next();
}
object.put("code", 0);
object.put("message", "查詢成功");
object.put("data", array);
} catch (SQLException e) {
object.put("code", 1);
object.put("message", "查詢失敗");
e.printStackTrace();
}
return object.toString();
}
}
SQLManager
package com.java.json;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLManager {
private Connection connection;
public Connection getConnection() {
return connection;
}
private static SQLManager manager;
public static SQLManager newInstance(){
if(manager==null){
manager=new SQLManager();
}
return manager;
}
private SQLManager(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/class";
String user="root";
String password="123456";
try {
Class.forName(driver);
connection=DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Servlet(JSON解析)
package com.java.json;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
/**
* Servlet implementation class Servlet
*/
@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Servlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json=request.getParameter("json");
System.out.println("得到的數據爲:"+json);
JSONObject object=JSONObject.fromObject(json);
String type=object.getString("type");
System.out.println(type);
String s="";
if(type.equals("Register")){
String userName=object.getJSONObject("data").getString("userName");
String password=object.getJSONObject("data").getString("password");
s=SQLOperate.newInstance().register(userName, password);
}else if(type.equals("Login")){
String userName=object.getJSONObject("data").getString("userName");
String password=object.getJSONObject("data").getString("password");
s=SQLOperate.newInstance().login(userName, password);
}else if(type.equals("Select")){
s=SQLOperate.newInstance().select();
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getWriter().append(s);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}