Serverlet 数据库连接、 doPost方法
public class Mysqlmanger {
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;
}
public static Mysqlmanger manger;
public static synchronized Mysqlmanger newInstance(){
if(manger==null){
manger=new Mysqlmanger();
}
return manger;
}
private Mysqlmanger(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/clazz";
String user="root";
String password="123456";
try {
Class.forName(driver);
connection=DriverManager.getConnection(url, user, password);
if(!connection.isClosed()){
statement=connection.createStatement();
String create="create table if not exists user(id int not null primary key auto_increment ,name varchar(30) not null,password varchar(30) not null)";
statement.execute(create);
}else{
System.out.println("请打开数据库");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Servlet implementation class MyServerlet
*/
@WebServlet("/MyServerlet")
public class MyServerlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServerlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName=request.getParameter("name");
String passWord=request.getParameter("password");
System.out.println("用户名:"+userName+" 密码:"+passWord);
userName=Encoding.doEncoding(userName);
passWord=Encoding.doEncoding(passWord);
Connection connection=Mysqlmanger.newInstance().getConnection();
try {
PreparedStatement preparedStatement=connection.prepareStatement("select * from user where name=? and password=?");
preparedStatement.setString(1, userName);
preparedStatement.setString(2, passWord);
ResultSet set=preparedStatement.executeQuery();
set.last();
int num=set.getRow();
if(num==1){
System.out.println("登录成功");
}else{
System.out.println("用户名或密码错误");
}
} catch (SQLException e) {
e.printStackTrace();
}
String s="用户名:"+userName+" 密码:"+passWord;
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);
}
}
public class Encoding {
public static String doEncoding(String string){
try {
byte[] array=string.getBytes("ISO-8859-1");
string=new String(array, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return string;
}
}
public class DoPost extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DoPost frame = new DoPost();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DoPost() {
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 btnDopost = new JButton("doPost方法");
btnDopost.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String urlstring="http://localhost:8080/MyServerTest/MyServerlet";
try {
URL url=new URL(urlstring);
HttpURLConnection httpconnect=(HttpURLConnection) url.openConnection();
httpconnect.setRequestMethod("POST");
httpconnect.setConnectTimeout(3000);
httpconnect.setReadTimeout(3000);
httpconnect.setRequestProperty("Accept-Charset", "utf-8");
httpconnect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpconnect.setDoOutput(true);
httpconnect.setUseCaches(false);
String parmas="name=john&password=123";
httpconnect.getOutputStream().write(parmas.getBytes());
int code=httpconnect.getResponseCode();
System.out.println("HTTP 状态码"+code);
if(code==HttpURLConnection.HTTP_OK){
InputStream is=httpconnect.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String line=br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}catch(SocketTimeoutException e){
System.out.println("连接服务器超时");
}catch (ConnectException e){
System.out.println("服务器拒绝连接");
} catch (IOException e) {
e.printStackTrace();
}
}
});
btnDopost.setBounds(117, 94, 125, 30);
contentPane.add(btnDopost);
}
}
HTTPClient
public class Mysqlmanger {
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;
}
public static Mysqlmanger manger;
public static synchronized Mysqlmanger newInstance(){
if(manger==null){
manger=new Mysqlmanger();
}
return manger;
}
private Mysqlmanger(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/clazz";
String user="root";
String password="123456";
try {
Class.forName(driver);
connection=DriverManager.getConnection(url, user, password);
if(!connection.isClosed()){
statement=connection.createStatement();
String create="create table if not exists user(id int not null primary key auto_increment ,name varchar(30) not null,password varchar(30) not null)";
statement.execute(create);
}else{
System.out.println("请打开数据库");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class Encoding {
public static String doEncoding(String string){
try {
byte[] array=string.getBytes("ISO-8859-1");
string=new String(array, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return string;
}
}
/**
* Servlet implementation class MyServerlet
*/
@WebServlet("/MyServerlet")
public class MyServerlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServerlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName=request.getParameter("name");
String passWord=request.getParameter("password");
System.out.println("用户名:"+userName+" 密码:"+passWord);
userName=Encoding.doEncoding(userName);
passWord=Encoding.doEncoding(passWord);
Connection connection=Mysqlmanger.newInstance().getConnection();
try {
PreparedStatement preparedStatement=connection.prepareStatement("select * from user where name=? and password=?");
preparedStatement.setString(1, userName);
preparedStatement.setString(2, passWord);
ResultSet set=preparedStatement.executeQuery();
set.last();
int num=set.getRow();
if(num==1){
System.out.println("登录成功");
}else{
System.out.println("用户名或密码错误");
}
} catch (SQLException e) {
e.printStackTrace();
}
String s="用户名:"+userName+" 密码:"+passWord;
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);
}
}
public class HttpClientDoGet extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HttpClientDoGet frame = new HttpClientDoGet();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public HttpClientDoGet() {
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 button = new JButton("登录");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String urlstring="http://localhost:8080/MyServerTest/MyServerlet?name=john&password=123";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient httpClient=builder.build();
HttpGet get=new HttpGet(urlstring);
get.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
try {
HttpResponse response=httpClient.execute(get);
StatusLine statusLine=response.getStatusLine();
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 (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
button.setBounds(120, 93, 123, 41);
contentPane.add(button);
}
}
public class HTTPClientDoPost extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HTTPClientDoPost frame = new HTTPClientDoPost();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public HTTPClientDoPost() {
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 button = new JButton("登录");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String urlstring="http://localhost:8080/MyServerTest/MyServerlet";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost post=new HttpPost(urlstring);
NameValuePair pair1=new BasicNameValuePair("name", "john");
NameValuePair pair2=new BasicNameValuePair("password", "123");
ArrayList<NameValuePair> params=new ArrayList<>();
params.add(pair1);
params.add(pair2);
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();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
button.setBounds(143, 80, 118, 45);
contentPane.add(button);
}
}