您的位置:首页 > 其它

8月13日---用户信息查询

2015-08-13 21:41 330 查看
用户可以通过与服务器连接在一个界面上实现登录,注册,找回密码的功能,与数据库进行交互

具体代码:

//服务器的代码
package com.lingzhuo.test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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.JSONArray;
import net.sf.json.JSONObject;

/**
* Servlet implementation class ServletTest
*/
@WebServlet("/ServletTest")
public class ServletTest extends HttpServlet {

// String name;
// String password;
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public ServletTest() {
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

//
String json = request.getParameter("json");
// System.out.println(json);
// String password = request.getParameter("password");
//
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// name= Encoding.doEncoding(name);
// password = Encoding.doEncoding(password);

if (null != json) {
JSONObject jsonObject = JSONObject.fromObject(json);
String type = jsonObject.getString("type");

JSONObject data = jsonObject.getJSONObject("data");
String name = data.getString("name");
String password = data.getString("password");
String s = "";

System.out.println("用户名: " + name + " " + "密码: " + password);
Connection con = MySQL.newInstance().getCon();
PreparedStatement prea;

if(type.equals("login")){
s=MethodOperator.newInstance().login(name, password);

}else if(type.equals("register")){
s=MethodOperator.newInstance().register(name, password);
}else if(type.equals("select")){
PreparedStatement prepare;
try {
prepare = con.prepareStatement("select * from user where username = ? ");
prepare.setString(1, name);
ResultSet set = prepare.executeQuery();
set.last();
int num = set.getRow();
if(num==1){
String passwordSelect = set.getString("password");
System.out.println(passwordSelect);
s=passwordSelect;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
// response.getWriter().append("Served at:
// ").append(request.getContextPath());
response.setHeader("Content-type", "text/html;charset=UTF-8");
// response.getWriter().append("用户名: "+name+"密码: "+password);

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);
}

}
//服务器所用到的方法
package com.lingzhuo.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import net.sf.json.JSONObject;

public class MethodOperator {
private static MethodOperator operator;
private MethodOperator(){

}
public static synchronized MethodOperator newInstance(){
if(operator==null){
operator = new MethodOperator();
}
return operator;
}
public String login(String name,String password){
PreparedStatement prea;
Connection con = MySQL.newInstance().getCon();
JSONObject obj = new JSONObject();
try {
prea = con.prepareStatement("select * from user where username = ? and password=?");
prea.setString(1, name);
prea.setString(2, password);
ResultSet set = prea.executeQuery();
set.last();
int num = set.getRow();
if(num==1){
obj.put("code", 1);//登录成功
}else{
obj.put("code", 0);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj.toString();
}
public String register(String name,String password){
JSONObject obj = new JSONObject();
PreparedStatement prea;
Connection con = MySQL.newInstance().getCon();

try {

prea = con.prepareStatement("select * from user where username = ? ");
prea.setString(1, name);

ResultSet set = prea.executeQuery();
set.last();
int num = set.getRow();
if(num==1){
obj.put("code", 0);//注册失败
}else{
String zhuce = "insert into user (username,password) values('" + name + "','" + password
+ "')";
prea.execute(zhuce);
obj.put("code", 1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj.toString();
}
}


//客户端的代码,带图像界面的
package com.lingzhuo.clientTest;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import net.sf.json.JSONObject;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.Font;

public class Login extends JFrame {

/**
*
*/

private JPanel contentPane;
private JTextField textField;
private JPasswordField passwordField;

/**
* 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() {
setBackground(Color.GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(Color.PINK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JLabel label = new JLabel("用户名");
label.setFont(new Font("楷体", Font.PLAIN, 18));
label.setBounds(57, 57, 54, 41);
contentPane.add(label);

JLabel label_1 = new JLabel("密码");
label_1.setFont(new Font("楷体", Font.PLAIN, 18));
label_1.setBounds(57, 124, 54, 53);
contentPane.add(label_1);

textField = new JTextField();
textField.setBounds(118, 60, 169, 38);
contentPane.add(textField);
textField.setColumns(10);

JButton btnNewButton = new JButton("登录");
btnNewButton.setFont(new Font("方正舒体", Font.PLAIN, 20));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String mima = new String(passwordField.getPassword());

String message = MyHTTPConnection.newInstance().creatConnection(textField.getText(),
mima, "login");
JSONObject obj = JSONObject.fromObject(message);
String code = obj.getString("code");
if (code.equals("0")) {
JOptionPane.showMessageDialog(null, "登录失败,请检查用户名或密码是否正确", "登录失败", JOptionPane.ERROR_MESSAGE);
System.out.println("登录失败");
} else {
JOptionPane.showMessageDialog(null, "登录成功", "登录成功", JOptionPane.ERROR_MESSAGE);
System.out.println("登陆成功");
}
}
});
btnNewButton.setBounds(106, 187, 93, 23);
contentPane.add(btnNewButton);

JButton button = new JButton("注册");
button.setFont(new Font("方正舒体", Font.PLAIN, 20));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
String password = new String(passwordField.getPassword());
Pattern username = Pattern.compile("\\w{3,}");
Matcher matcher = username.matcher(name);
boolean b = matcher.matches();

Pattern pass = Pattern.compile("\\w{3,}");
Matcher matcherPass = pass.matcher(password);
boolean b1 = matcherPass.matches();
if (!b) {
JOptionPane.showMessageDialog(null, "用户名不合规定,请重新注册", "注册失败", JOptionPane.ERROR_MESSAGE);
} else if (!b1) {
JOptionPane.showMessageDialog(null, "密码不合规定,请重新注册", "注册失败", JOptionPane.ERROR_MESSAGE);
} else {
String mima = new String(passwordField.getPassword());
String message = MyHTTPConnection.newInstance().creatConnection(textField.getText(),
mima, "register");
JSONObject obj = JSONObject.fromObject(message);
String code = obj.getString("code");
if (code.equals("0")) {
JOptionPane.showMessageDialog(null, "注册失败,用户名已存在", "注册失败", JOptionPane.ERROR_MESSAGE);

System.out.println("注册失败");
} else {
JOptionPane.showMessageDialog(null, "注册成功", "注册成功", JOptionPane.ERROR_MESSAGE);
System.out.println("注册成功");
}
}

}
});
button.setBounds(221, 187, 93, 23);
contentPane.add(button);

JLabel label_2 = new JLabel("找回密码");
label_2.setFont(new Font("楷体", Font.PLAIN, 20));
label_2.setForeground(Color.PINK);
label_2.setBounds(309, 134, 93, 32);
contentPane.add(label_2);
label_2.setForeground(Color.BLUE);

passwordField = new JPasswordField();
passwordField.setBounds(121, 126, 166, 38);
contentPane.add(passwordField);

label_2.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

String back = MyHTTPConnection.newInstance().creatConnection(textField.getText(), new String(passwordField.getPassword()),
"select");
// System.out.println(back);
JOptionPane.showMessageDialog(null, "密码是" + back, "找回密码", JOptionPane.ERROR_MESSAGE);
}
});

}
}
//与数据库进行连接及客户端用到的方法
package com.lingzhuo.clientTest;

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 MyHTTPConnection {
private MyHTTPConnection(){

}
private static MyHTTPConnection connection;
public static synchronized MyHTTPConnection newInstance(){
if(connection==null){
connection = new MyHTTPConnection();
}
return connection;
}
public String creatConnection(String name,String password,String type){
String urlString = "http://localhost:8088/WebTest/ServletTest";
HttpClientBuilder builder =HttpClientBuilder.create();
builder.setConnectionTimeToLive(1000, TimeUnit.MILLISECONDS);
HttpClient client = builder.build();
HttpPost post = new HttpPost(urlString);

JSONObject obj = new JSONObject();
obj.put("type", type);
JSONObject data = new JSONObject();
data.put("name", name);
data.put("password", password);
obj.put("data", data);

NameValuePair pair = new BasicNameValuePair("json", obj.toString());

ArrayList<NameValuePair> params = new ArrayList<>();
params.add(pair);

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 e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}

}


结果截图:

主界面:



登录:



注册:



找回密码:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: