目录
数据库
单例设计模式
单例设计模式与数据库的结合
PreparedStatement
MVC设计模式
事务
服务器
项目(数据库—服务器—网络)
数据库
MySQL(在windows下忽略大小写)
DATABASE 数据库
TABLE 表
字段 属性 主键(一个TABLE中不能重复,能够使用这个值确定一条数据) 外键(一个表中的数据持有别的表中的主键)
auto_increment 主键自增长
创建数据库
CREATE DATABASE Clazz
创建表
CREATE TABLE Student(Sno int NOT NULL PRIMARY KEY AUTO_INCREMENT,Sname varchar(30) NOT NULL, Ssex char(3),Sage char(3));
增 insert
insert into Student values (1,'King','男','21')
删 delete
delete from Student where Sname = 'Gone'
改 update
update Student set Sage = '25' where Sname = 'Went'
查 select
select Sname,Ssex,Sage from Student where Sage>20
/**
* jdbc的连接测试
*
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
// 连接数据库的驱动
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名
String url = "jdbc:mysql://localhost:3306/Clazz";
// MySQL配置时的用户名
String user = "root";
// java连接MySQL配置时的密码
String password = "123456";
try {
Class.forName(driver);//加载驱动
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String insert = "insert into Student (Sname,Ssex,Sage) values('WZ','男','28')";// 增
String delete = "delete from Student where Sno = '2012200968'";// 删
String update = "update Student set Sname = 'Wz' where Sname = 'WZ'";// 改
String select = "select * from Student";// 查 //
// statement.execute(insert);// 增、删、改的时候用execute()
ResultSet resultSet = statement.executeQuery(select);// 查的时候用executeQuery()
resultSet.first();// 先把游标放在第一位
while (!resultSet.isAfterLast()) {// 判断游标是否在最后一位的后边
String name = resultSet.getString("Sname");
String age = resultSet.getString("Sage");
resultSet.next();// 游标下移
System.out.println(name+" "+age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
结果
单例设计模式
单例设计模式
让其他类调用时只创建一个对象
1、将构造器改为private修饰
2、私有静态属性
3、写一个public static(可以加一个锁,防止多线程是创建多个对象)方法 用static可以
单例设计模式与数据库的结合
public class SQLManager {
//单例设计模式
private Statement statement;
public Statement getStatement() {
return statement;
}
public void setStatement(Statement statement) {
this.statement = statement;
}
//2、声明私有静态本类的对象
private static SQLManager manager;
//3、静态公有的线程锁的方法 返回当前类的对象
public static synchronized SQLManager newInstence(){
if (manager == null) {
manager = new SQLManager();
}
return manager;
}
//1、私有构造方法
private SQLManager(){
//连接数据库的驱动
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名
String url = "jdbc:mysql://localhost:3306/Users";
//MySQL配置时的用户名
String user = "root";
//java连接MySQL配置时的密码
String password = "123456";
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
if (!connection.isClosed()) {
statement = connection.createStatement();
statement.execute("create table if not exists user"
+ "(id int NOT NULL PRIMARY KEY AUTO_INCREMENT ,user_name varchar(30) NOT NULL,password varchar(20))");
System.out.println("已连接");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注册时
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String username = textField.getText();
char[] passwords = passwordField.getPassword();//得到密码框中显式密码,返回的是char[]
String password = "";
for (int i = 0; i < passwords.length; i++) {
password += passwords[i];
}
//用正则表达式检测用户名和密码是否符合规范
Pattern patternName = Pattern.compile("^\\w+$");
Matcher matcherName = patternName.matcher(username);
boolean name = matcherName.matches();
Pattern patternPassword = Pattern.compile("^\\w+$");
Matcher matcherPassword = patternPassword.matcher(password);
boolean word = matcherPassword.matches();
if (name&&word) {
Statement statement = SQLManager.newInstence().getStatement();
String select = String.format("select * from user where user_name = '%s'", username);
try {
ResultSet result = statement.executeQuery(select);
result.last();//找到符合用户名的信息的最后一个
int i = result.getRow();//得到最后一个符合用户名的行数
if (i>0) {
System.out.println("此用户已注册");
}else {
String insert = String.format("insert into user(user_name,password) values('%s','%s')", username,password);
statement.execute(insert);
System.out.println("注册成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
}else if (!name) {
System.out.println("名称不符合注册标准");
}else if (!word) {
System.out.println("密码不符合标准");
passwordField.setText("");
}
}
});
登录时
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Statement st = SQLManager.newInstence().getStatement();
String username = textField.getText();
char[] passwords = passwordField.getPassword();
String password = "";
for (char c : passwords) {
password += c;
}
String select = String.format("select * from user where user_name = '%s' and password = '%s'", username,password);
try {
ResultSet result = st.executeQuery(select);
result.last();
int num = result.getRow();
if (num>0) {
System.out.println("登录成功");
}else {
System.out.println("未注册");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
PreparedStatement
Statement时’or 1=’1 会自登陆,对程序造成影响
一般用PreparedStatement
statement.setString(1, username);第一个参数是语句中的第几个”?”,第二个参数是当前”?”需要传入的值。
public boolean SignIn(String username,String password) {
Connection connection = SQLManager.newInstence().getConnection();
try {
if (!connection.isClosed()) {
//用PreparedStatement消除'or 1='1的现象
PreparedStatement preparedStatement = connection.prepareStatement("select * from user where user_name = ? and password = ?");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.last();
int num = resultSet.getRow();
return num == 1;
}
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
return false;
}
MVC设计模式
一种设计模式,也是一种必须学会的编程思想
Model-View-Control
模型(model)-视图(view)-控制器(controller)。模型、视图、控制器的分层处理
/**
* 此类只进行数据库的连接
* @author Administrator
*
*/
public class SQLManager {
//单例设计模式
private Statement statement;
private Connection connection;
public Connection getConnection() {
return connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
public Statement getStatement() {
return statement;
}
public void setStatement(Statement statement) {
this.statement = statement;
}
//2、声明私有静态本类的对象
private static SQLManager manager;
//3、静态公有的线程锁的方法 返回当前类的对象
public static synchronized SQLManager newInstence(){
if (manager == null) {
manager = new SQLManager();
}
return manager;
}
//1、私有构造方法
private SQLManager(){
init();
}
public void init(){
//连接数据库的驱动
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名
String url = "jdbc:mysql://localhost:3306/Users";
//MySQL配置时的用户名
String user = "root";
//java连接MySQL配置时的密码
String password = "123456";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 此类只进行数据库中的信息交互
* @author Administrator
*
*/
public class SQLOperate {
private SQLOperate() {
}
public synchronized static SQLOperate newInstance(){
if (operate == null) {
operate = new SQLOperate();
}
return operate;
}
private static SQLOperate operate;
/**
* 用户登录的数据操作
* @param username 用户名
* @param password 密码
* @return 如果true表示登录成功,false表示登录失败
*/
public boolean SignIn(String username,String password) {
Connection connection = SQLManager.newInstence().getConnection();
try {
if (!connection.isClosed()) {
//用PreparedStatement消除'or 1='1的现象
PreparedStatement preparedStatement = connection.prepareStatement("select * from user where user_name = ? and password = ?");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.last();
int num = resultSet.getRow();
return num == 1;
}
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
return false;
}
/**
* 用户注册时的数据操作
* @param username 用户名
* @param password 用户密码
*/
public void DengLu(String username,String password){
Connection connection = SQLManager.newInstence().getConnection();
try {
PreparedStatement statement = connection.prepareStatement("select * from user where user_name = ?");
statement.setString(1, username);
ResultSet set = statement.executeQuery();
set.last();
int num = set.getRow();
if (num>0) {
System.out.println("此用户名已注册");
}else {
PreparedStatement statement2 = connection.prepareStatement("insert into user(user_name,password) values(?,?)");
statement2.setString(1, username);
statement2.setString(2, password);
statement2.execute();
System.out.println("注册成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//注册的视图(部分)
public void actionPerformed(ActionEvent arg0) {
String username = textField.getText();
char[] passwords = passwordField.getPassword();//得到密码框中显式密码,返回的是char[]
String password = "";
for (int i = 0; i < passwords.length; i++) {
password += passwords[i];
}
//用正则表达式检测用户名和密码是否符合规范
Pattern patternName = Pattern.compile("^\\w+$");
Matcher matcherName = patternName.matcher(username);
boolean name = matcherName.matches();
Pattern patternPassword = Pattern.compile("^\\w+$");
Matcher matcherPassword = patternPassword.matcher(password);
boolean word = matcherPassword.matches();
if (name&&word) {
SQLOperate.newInstance().DengLu(username, password);//调用数据库造作类中的方法,实现分层
}else if (!name) {
System.out.println("名称不符合注册标准");
}else if (!word) {
System.out.println("密码不符合标准");
passwordField.setText("");
}
}
//登录时的视图(部分)
public void actionPerformed(ActionEvent e) {
String username = textField.getText();
char[] passwords = passwordField.getPassword();
String password = "";
for (char c : passwords) {
password += c;
}
boolean isSignIn = SQLOperate.newInstance().SignIn(username, password);
if (isSignIn) {
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
}
事务
事务(一组不可拆分的操作) 关键字commit
例:银行ATM提款 输入金额-播放录音-打开取钱口-吐钱-钱拿。其中有一个出错就无法取款。即回滚到初始位置
//将connection设置为不自动提交
connection.setAutoCommit(false);
…需要执行的代码块
statement.addBatch(sql)将sql语句添加到执行列表中统一执行
statement.executeBatch();执行列表中的语句
(可以提高SQL语句的执行效率)
…
connection.commit();//从connection.setAutoCommit(false)到commit是一个事务,中间一条出错,会回滚至前边。
String sql1 = "insert into user(user_name,password) values ('fsdkjhs','sdf')";
String sql2 = "insert into user(user_name,password) values ('fsdkjs','sdfd')";
String sql3 = "insert into user(user_name,passwords) values ('fsdkjdashs','sddfsf')";
String sql4 = "insert into user(user_name,password) values ('fs','sdf')";
String sql5 = "insert into user(user_name,password) values ('ffdssdkjhs','sdsf')";
//数据库连接默认每一条sql语句是一个事务,会单独执行,自动提交
//将connection设置为不自动提交
connection.setAutoCommit(false);
// statement.addBatch(sql)将sql语句添加到执行列表中统一执行
statement.addBatch(sql1);
statement.addBatch(sql2);
statement.addBatch(sql3);
statement.addBatch(sql4);
statement.addBatch(sql5);
statement.executeBatch();
connection.commit();//从connection.setAutoCommit(false)到commit是一个事务,中间一条出错,会回滚至前边。
服务器
搭建一个服务器 创建serverlet用来给前端提供数据使用tomcat
新建一个Dynamic Web Project
在WebContent中新建一个index.xml如图
在index.xml中的
<body>
<a> HelloWorld!</a>
</body>
运行后如图:
将其生成的地址复制到浏览器上:
搭建一个简易服务器:
搭建服务器ServLet
HTTpUrlConnection
HTTpClient
(服务器与用户之间的信息交互)
新建一个Servlet
soGet 直接连接在url后边,是显式的
doPost 隐式的,比doGet安全
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//其中第一个参数是指用户向服务器提交的数据。
//第二个参数是指服务器向用户发送的数据。
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
doGet方法在网址后边跟上要提交的数据 用?隔开,例如:
localhost:8080/MyServiceTest?username=zhangsan&password=1234
注:”?”前没有”/”
用户与服务器之间的交互:(doGet方法)
使用浏览器提交数据默认的编码格式ISO-8859-1 得到string username编码格式8859-1
/**
* 此类为汉字编码的转变类
* @author Administrator
*
*/
public class Encoding {
/**
* 将ISO-8859-1的字符串转换成UTF-8的字符串
* @param string 需要转换的字符串
* @return 返回转换好的字符串
*/
public static String getEncoding(String string) {
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;
}
}
/**
* Servlet implementation class MyServlet
*/
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
String username = request.getParameter("username");
String passwrod = request.getParameter("password");
username = Encoding.getEncoding(username);//将用户提交给服务器的ISO-8859-1字符串转型成UTF-8
String s = "得到的用户名:"+username+"密码:"+passwrod;
System.out.println(s);
response.setHeader("Content-type", "text/html;charset=UTF-8");
//让浏览器以UTF-8编码格式解析
response.getWriter().append(s);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
HTTpUrlConnection
doGet方法
/**
* HTTpUrlConnection的doGet方法
* @param username 用户名
* @param password 密码
*/
public void HTTpUrldoGet(String username, String password) {
String urlString = "http://localhost:8080/HTTpTest_Servelet//ServeletTest?username=" + username + "&"
+ "password=" + password;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置接受的数据类型
connection.setRequestProperty("Accept-Charset", "utf-8");
// 设置可以接受序列化的java对象
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
int code = connection.getResponseCode();
System.out.println(code);
if (code == HttpURLConnection.HTTP_OK) {
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
doPost方法
/**
* HTTpUrlConnection的doPost方法
* @param username 用户名
* @param password 密码
*/
public void HTTpUrldoPost(String username, String password) {
String urlString = "http://localhost:8080/HTTpTest_Servelet//ServeletTest";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置接受的数据类型
connection.setRequestProperty("Accept-Charset", "utf-8");
// 设置可以接受序列化的java对象
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置可以读取服务器返回的信息,默认为ture
connection.setDoInput(true);
//设置客户端可以给服务器提交信息,默认是false。post方法必须设置为true
connection.setDoOutput(true);
//post方法不允许使用缓存
connection.setUseCaches(false);
String params = "username="+username+"&password="+password;
connection.getOutputStream().write(params.getBytes());
int code = connection.getResponseCode();
System.out.println(code);
if (code == HttpURLConnection.HTTP_OK) {
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line = br.readLine();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
HTTpClient
doGet方法
/**
* HTTpClient的doGet方法
* @param username 用户名
* @param password 密码
*/
public static void HTTpClientdoGet(String username,String password) {
String urlString = "http://localhost:8080/HTTpTest_Servelet//ServeletTest?username=" + username + "&"
+ "password=" + password;
HttpClientBuilder builder = HttpClientBuilder.create();//创建HttpClientBuilder
HttpClient client = builder.build();
HttpGet get = new HttpGet(urlString);//得到get方法
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设定服务器接收后数据的读取方式为utf-8
try {
HttpResponse response = client.execute(get);//执行
StatusLine statusLine = response.getStatusLine();//获得返回的的表头,包含HTTp状态码
int code = statusLine.getStatusCode();//获得HTTp状态码
System.out.println(code);
if (code == HttpURLConnection.HTTP_OK) {
HttpEntity entity = response.getEntity();//得到返回的数据实体
InputStream is = entity.getContent();//得到输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line = br.readLine();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
doPost方法
/**
* HTTpClient的doPost方法
* @param username 用户名
* @param password 密码
*/
public static void HTTpClientdoPost(String username,String password) {
String urlString = "http://localhost:8080/HTTpTest_Servelet//ServeletTest";
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClient client = builder.build();
HttpPost post = new HttpPost(urlString);//设置post方法
NameValuePair pair1 = new BasicNameValuePair("username", username);//设置参数
NameValuePair pair2 = new BasicNameValuePair("password", password);
ArrayList<NameValuePair> list = new ArrayList<>();//将参数放进参数列表
list.add(pair1);
list.add(pair2);
try {
post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));//设置发送到服务器的数据的格式为utf-8
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设定服务器接收后数据的读取方式为utf-8
HttpResponse response = client.execute(post);//执行
StatusLine statusLine = response.getStatusLine();//获得返回过来的表头,包含Http的状态码
int code = statusLine.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();
while(line!=null){
System.out.println(line);
line = br.readLine();
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
项目(网络—服务器—数据库)
1.服务器导包tomact。lib文件夹下mysql包、json包
2.界面中导包json包
注意:MVC编程思想
界面:
//登录的按钮
JButton btnHttpclientdopost = new JButton("登录");
btnHttpclientdopost.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = textField.getText();
char[] array = passwordField.getPassword();
String password = "";
for (char c : array) {
password += c;
}
//用正则表达式检测用户名和密码是否符合规范
Pattern patternName = Pattern.compile("^\\w+$");
Matcher matcherName = patternName.matcher(username);
boolean name = matcherName.matches();
Pattern patternPassword = Pattern.compile("^\\w+$");
Matcher matcherPassword = patternPassword.matcher(password);
boolean word = matcherPassword.matches();
if (name&&word) {
String line = HttpClientOperate.newInstance().login(username, password);
System.out.println(line);//调用网络操作中的登录方法
//显示登录后的界面
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SelectFrame frame = new SelectFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
}else if (!name) {
System.out.println("名称不符合注册标准");
}else if (!word) {
System.out.println("密码不符合标准");
passwordField.setText("");
}
//注册的按钮
JButton button = new JButton("还没注册?注册");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//调用注册的界面
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterFrame frame = new RegisterFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
/**登录后的界面按钮*/
JButton button = new JButton("查询所有人");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String line = HttpClientOperate.newInstance().select();//调用网络操作中的查询方法
System.out.println(line);
// textArea.setText(line);
}
});
/**注册的界面按钮*/
JButton button = new JButton("注册");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
HttpClientOperate.newInstance().setType("register");//设置reister注册的type
String username = textField.getText();
char[] array = passwordField.getPassword();
String password = "";
for (char c : array) {
password += c;
}
//用正则表达式检测用户名和密码是否符合规范
Pattern patternName = Pattern.compile("^\\w+$");
Matcher matcherName = patternName.matcher(username);
boolean name = matcherName.matches();
Pattern patternPassword = Pattern.compile("^\\w+$");
Matcher matcherPassword = patternPassword.matcher(password);
boolean word = matcherPassword.matches();
if (name&&word) {
String line = HttpClientOperate.newInstance().register(username, password);//调用网络操作中的注册方法
System.out.println(line);
}else if (!name) {
System.out.println("名称不符合注册标准");
}else if (!word) {
System.out.println("密码不符合标准");
passwordField.setText("");
}
}
});
点击按钮后的网络操作
/**
* 点击按钮后的网络操作
* @author Administrator
*
*/
public class HttpClientOperate {
public HttpClientOperate() {
}
private static HttpClientOperate operate;
public static HttpClientOperate newInstance() {
if (operate == null) {
operate = new HttpClientOperate();
}
return operate;
}
/**
* 根据type得到Register 将json提交到服务器,并接收服务器返回的json,并解析
* @param username
* @param password
* @return 返回json
*/
public String register(String username,String password) {
JSONObject object = new JSONObject();
object.put("type", "Register");
JSONObject data = new JSONObject();
data.put("username", username);
data.put("password", password);
object.put("data", data);
String urlString = "http://localhost:8080/MyServiceTest//MyServlet";
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClient client = builder.build();
HttpPost post = new HttpPost(urlString);
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();
System.out.println(code);
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);
line = br.readLine();
}
return buffer.toString();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 根据type得到Login 将json提交到服务器,并接收服务器返回的json,并解析
* @param username
* @param password
* @return 返回json
*/
public String login(String username,String password) {
JSONObject object = new JSONObject();
object.put("type", "Login");
JSONObject data = new JSONObject();
data.put("username", username);
data.put("password", password);
object.put("data", data);
String urlString = "http://localhost:8080/MyServiceTest//MyServlet";
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClient client = builder.build();
HttpPost post = new HttpPost(urlString);
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();
System.out.println(code);
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);
line = br.readLine();
}
return buffer.toString();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 根据type得到Select 将json提交到服务器,并接收服务器返回的json,并解析
* @param username
* @param password
* @return 返回json
*/
public String select() {
JSONObject object = new JSONObject();
object.put("type", "Select");
String urlString = "http://localhost:8080/MyServiceTest//MyServlet";
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClient client = builder.build();
HttpPost post = new HttpPost(urlString);
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();
System.out.println(code);
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);
line = br.readLine();
}
return buffer.toString();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
服务器Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//用户通过浏览器向服务器提交信息且输出
String json = request.getParameter("json");
JSONObject obj = JSONObject.fromObject(json);//根据json串得到jsonobject
String type = obj.getString("type");
String massage = "";
//根据type调用不同的方法
if (type.equals(Types.REGISTER)) {
JSONObject data = obj.getJSONObject("data");
String username = data.getString("username");
String password = data.getString("password");
massage = SQLOperate.newIntence().returnRegistMsg(username, password);//调用服务器数据库操作类中的注册方法
}
else if (type.equals(Types.LOGIN)) {
JSONObject data = obj.getJSONObject("data");
String username = data.getString("username");
String password = data.getString("password");
massage = SQLOperate.newIntence().renturnLogin(username, password);//调用服务器数据库操作类中的登录方法
}else if (type.equals(Types.SELECT)) {
massage = SQLOperate.newIntence().renturnSelect();//调用服务器数据库操作类中的查询方法
}
response.setHeader("Content-type", "text/html;charset=UTF-8");//让浏览器以UTF-8编码格式解析
//服务器响应客户端的信息
response.getWriter().append(massage);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
/**
* 注册类型的常量类
* @author Administrator
*
*/
public class Types {
/**注册的类型*/
public static final String REGISTER = "Register";
/**登录的类型*/
public static final String LOGIN = "Login";
/**查询的类型*/
public static final String SELECT = "Select";
}
服务器的数据库连接类
/**
* 数据库连接类
* @author Administrator
*
*/
public class SQLManage {
private Connection connection;
public Connection getConnection() {
return connection;
}
private static SQLManage manage;
public static synchronized SQLManage newInstance() {
if (manage == null) {
manage = new SQLManage();
}
return manage;
}
private SQLManage(){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/users";
String user = "root";
String password = "123456";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务器的数据库操作类
/**
* 数据库操作类
* @author Administrator
*
*/
public class SQLOperate {
public SQLOperate() {
}
private static SQLOperate operate;
public static synchronized SQLOperate newIntence() {
if (operate == null) {
operate = new SQLOperate();
}
return operate;
}
/**
* 数据库中注册的方法
* @param username 用户名
* @param passwrod 密码
* @return 返回结果信息
*/
public String returnRegistMsg(String username,String password) {
int code = 0;
JSONObject obj = new JSONObject();
Connection connection = SQLManage.newInstance().getConnection();
try {
PreparedStatement statement = connection.prepareStatement("select * from user where user_name = ?");
statement.setString(1, username);
ResultSet set = statement.executeQuery();
set.last();
int num = set.getRow();
if (num>0) {
obj.put("code", 0);
obj.put("message", "用户名被注册");
}else {
PreparedStatement statement2 = connection.prepareStatement("insert into user(user_name,password)values(?,?)");
statement2.setString(1, username);
statement2.setString(2, password);
statement2.execute();
obj.put("code", 1);
obj.put("message", "注册成功");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
obj.put("code", 0);
obj.put("message", "注册失败");
e.printStackTrace();
}
return obj.toString();
}
/**
* 数据库中登录的方法
* @param username 用户名
* @param passwrod 密码
* @return 返回结果信息
*/
public String renturnLogin(String username,String password){
int code = 0;
JSONObject obj = new JSONObject();
Connection connection = SQLManage.newInstance().getConnection();
try {
PreparedStatement statement =connection.prepareStatement("select * from user where user_name = ?");
statement.setString(1, username);
ResultSet resultSet = statement.executeQuery();
resultSet.last();
int num = resultSet.getRow();
if (num>0) {
PreparedStatement statement2 = connection.prepareStatement("select * from user where password = ? and user_name = ?");
statement2.setString(1, password);
statement2.setString(2, username);
ResultSet resultSet2 = statement2.executeQuery();
resultSet2.last();
int num2 = resultSet2.getRow();
if (num2>0) {
obj.put("code", 1);
obj.put("massage", "登陆成功");
}else {
obj.put("code",0 );
obj.put("massage", "密码不正确");
}
}else {
obj.put("code", 2);
obj.put("massage", "此用户未注册");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
obj.put("code", 0);
obj.put("massage", "登录失败");
e.printStackTrace();
}
return obj.toString();
}
/**
* 数据库中查询的方法
* @return 返回结果信息
*/
public String renturnSelect(){
int code = 0;
JSONObject obj = new JSONObject();
Connection connection = SQLManage.newInstance().getConnection();
try {
PreparedStatement statement =connection.prepareStatement("select * from user ");
ResultSet resultSet = statement.executeQuery();
resultSet.first();
JSONArray array = new JSONArray();
while(!resultSet.isAfterLast()){
JSONObject item = new JSONObject();
item.put("name", resultSet.getString("user_name"));
array.add(item);
resultSet.next();
}
obj.put("code", 1);
obj.put("name", array);
obj.put("massage", "成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
obj.put("code", 0);
obj.put("massage", "查询失败");
e.printStackTrace();
}
return obj.toString();
}
}