1、右键在web里面找到Dynamic web project,建立一个服务器,在Java Resources中建一个一个包,写入需要用到的代码,还需要在这个包里建一个servlet(里面包含了DoGet和DoPost的方法)然后导入所需的jar包。在这个程序中需要导入json_jar包和mysql_jdbc.jar包(导入到WebContent下的WEB-INF下的lib里面)。
**********************SQLManager***************
public class SQLManager {
private static SQLManager manager;
private Connection connection;
public Connection getConnection() {
return connection;
}
public static synchronized SQLManager newInstance(){
if(manager==null){
manager=new SQLManager();
}
return manager;
}
private SQLManager(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/clazz";
String user="root";
String password="654321";
try {
Class.forName(driver);
connection=DriverManager.getConnection(url, user, password);
connection.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
*************************SQLOperate*****************
public class SQLOperate {
public static final int SUCESS=0;
public static final int ERRO=1;
private SQLOperate(){
}
private static SQLOperate operate;
public static synchronized SQLOperate newInstance(){
if(operate==null){
operate=new SQLOperate();
}
return operate;
}
public String register(String userName,String password){
JSONObject obj=new JSONObject();
Connection conn=SQLManager.newInstance().getConnection();
try {
PreparedStatement state=conn.prepareStatement("select * from user where user_name=?");
state.setString(1, userName);
ResultSet set=state.executeQuery();
set.last();
int num=set.getRow();
if(num>0){
obj.put("code", 1);
obj.put("message", "该用户名已被注册");
return obj.toString();
}
PreparedStatement state1=conn.prepareStatement("insert into user (user_name,user_password)values(?,?)");
state1.setString(1, userName);
state1.setString(2, password);
state1.execute();
obj.put("code", 0);
obj.put("message", "成功注册");
} catch (SQLException e) {
obj.put("code", 1);
obj.put("message", "注册失败");
e.printStackTrace();
}
return obj.toString();
}
public String login(String userName,String password){
System.out.println("服务器查询数据库"+userName+password);
JSONObject obj=new JSONObject();
Connection conn=SQLManager.newInstance().getConnection();
try {
PreparedStatement state=conn.prepareStatement("select * from user where user_name=?");
state.setString(1, userName);
ResultSet set=state.executeQuery();
set.last();
int num=set.getRow();
if(num==0){
obj.put("code", 1);
obj.put("message", "用户名错误");
return obj.toString();
}
PreparedStatement state2=conn.prepareStatement("select * from user where user_name=? and user_password=?");
state2.setString(1, userName);
state2.setString(2, password);
ResultSet set2=state2.executeQuery();
set2.last();
int num2=set2.getRow();
if(num2>0){
obj.put("code", 0);
obj.put("message", "登录成功");
return obj.toString();
}
} catch (SQLException e) {
obj.put("code", 1);
obj.put("message", "登录失败");
e.printStackTrace();
}
return obj.toString();
}
public String select(){
JSONObject obj=new JSONObject();
Connection conn=SQLManager.newInstance().getConnection();
try {
PreparedStatement state=conn.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("user_password"));
item.put("username", set.getString("user_name"));
array.add(item);
set.next();
}
obj.put("code", 0);
obj.put("message", "查询成功");
obj.put("data", array);
} catch (SQLException e) {
obj.put("code", 1);
obj.put("message", "查询失败");
e.printStackTrace();
}
return obj.toString();
}
*************************Register******************
public class Register {
public void register(){
}
}
********************MyTestServerlet********************
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 MyTestServerlet */
@WebServlet("/MyTestServerlet")
public class MyTestServerlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/** * @see HttpServlet#HttpServlet() */
public MyTestServerlet() {
super();
// TODO Auto-generated constructor stub
}
/** * @see/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json=request.getParameter("json");
String back="";
// {type:"register",data:{username:"zhangsan",password:"123456"}}
System.out.println("得到的数据:"+json);
//创建json对象,传入json数据
JSONObject obj=JSONObject.fromObject(json);
String type=obj.getString("type");
if(type.equals(Config.REGISTER)){
JSONObject data=obj.getJSONObject("data");
String userName=data.getString("username");
String password=data.getString("password");
back=SQLOperate.newInstance().register(userName, password);
}else if(type.equals("Login")){
JSONObject data=obj.getJSONObject("data");
String userName=data.getString("username");
String password=data.getString("password");
back=SQLOperate.newInstance().login(userName, password);
}else if(type.equals("Select")){
back=SQLOperate.newInstance().select();
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
//让浏览器以utf-8编码格式解析
response.getWriter().append(back);
}
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
******************Encoding*****************
public class Encoding {
public static String doEncoding(String string) {
if(string==null){
return null;
}
try {
byte[] array = string.getBytes("ISO-8859-1");
string = new String(array, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return string;
}
**************Config*********************
public class Config {
/**注册的类型*/
public static final String REGISTER="register";
}
**************MyHttpMethod*************
public class MyHttpMethod {
private MyHttpMethod() {
}
private static MyHttpMethod manager;
public static synchronized MyHttpMethod newInstance() {
if (manager == null) {
manager = new MyHttpMethod();
}
return manager;
}
public String register(String username, String password) {
String url = "http://localhost:8080/MyServerTest/MyTestServerlet";
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client = builder.build();
HttpPost post = new HttpPost(url);// 设置为Post方法
JSONObject obj = new JSONObject();// {}
obj.put("type", "register");// {type:"register"}
JSONObject data = new JSONObject();// {}
data.put("username", username);// {username:"zhangsan"}
data.put("password", password);// {username:"zhangsan",password:"123456"}
obj.put("data", data);// {type:"register",data:{username:"zhangsan",password:"123456"}}
NameValuePair pair1 = new BasicNameValuePair("json", obj.toString());
ArrayList<NameValuePair> params = new ArrayList<>();
params.add(pair1);
try {
post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
// 设置服务器接收后数据的读取方式为UTF-8
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//执行Post方法得到服务器返回的所有数据都在response中
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));
String line = br.readLine();
//带有缓冲区的字符串是可变的,append方法是字符连接
StringBuffer buffer = new StringBuffer();
while (line != null) {
buffer.append(line);
System.out.println(line);
line = br.readLine();
}
return buffer.toString();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String login(String username, String password) {
System.out.println("客户端传输"+username+password);
String url = "http://localhost:8080/MyServerTest/MyTestServerlet";
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client = builder.build();
HttpPost post = new HttpPost(url);// 设置为Post方法
JSONObject obj = new JSONObject();// {}
obj.put("type", "Login");// {type:"Login"}
JSONObject data = new JSONObject();// {}
data.put("username", username);// {username:"zhangsan"}
data.put("password", password);// {username:"zhangsan",password:"123456"}
obj.put("data", data);// {type:"register",data:{username:"zhangsan",password:"123456"}}
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 == HttpURLConnection.HTTP_OK) {
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) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String select() {
String url = "http://localhost:8080/MyServerTest/MyTestServerlet";
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");// {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 == HttpURLConnection.HTTP_OK) {
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) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class MyHttpManager {
private MyHttpManager() {
}
private static MyHttpManager manager;
public static synchronized MyHttpManager newInstance() {
if (manager == null) {
manager = new MyHttpManager();
}
return manager;
}
}
package com.lingzhuo.register;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.lingzhuo.http.MyHttpMethod;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainJFrame 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 {
MainJFrame frame = new MainJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public MainJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 477, 343);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(189, 54, 149, 47);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(189, 165, 153, 47);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblNewLabel = new JLabel("用户名");
lblNewLabel.setBounds(89, 70, 70, 23);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("密码");
lblNewLabel_1.setBounds(89, 181, 82, 23);
contentPane.add(lblNewLabel_1);
JButton btnNewButton = new JButton("登录");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String message=MyHttpMethod.newInstance().login(textField.getText(),textField_1.getText());
// System.out.println(message);
}
});
btnNewButton.setBounds(211, 233, 102, 31);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("注册");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
btnNewButton_1.setBounds(125, 274, 93, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("忘记密码");
btnNewButton_2.setBounds(280, 274, 93, 23);
contentPane.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("查询所有用户");
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message=MyHttpMethod.newInstance().select();
// System.out.println(message);
}
});
btnNewButton_3.setBounds(358, 28, 93, 23);
contentPane.add(btnNewButton_3);
}
}
public class Register 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 {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * 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);
textField = new JTextField();
textField.setBounds(150, 44, 185, 51);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(159, 138, 176, 45);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton btnNewButton = new JButton("注册");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String message=MyHttpMethod.newInstance().register(textField.getText(), textField_1.getText());
// System.out.println(message);
}
});
btnNewButton.setBounds(201, 209, 101, 29);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("用户名");
lblNewLabel.setBounds(64, 62, 76, 22);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("密码");
lblNewLabel_1.setBounds(62, 153, 78, 30);
contentPane.add(lblNewLabel_1);
}
}
注意:
先运行MyTestServerlet在运行 MainJFrame