一、未添加数据库的GET和POST方法
1、serverlet服务器的搭建在前面的博客中已经想写描述,此处不再赘述。
2、serverlet代码:
package com.augtwleve;
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;
/** * Servlet implementation class MyserverletTestyuanchuang */
@WebServlet("/MyserverletTestyuanchuang")
public class MyserverletTestyuanchuang extends HttpServlet {
private static final long serialVersionUID = 1L;
/** * @see HttpServlet#HttpServlet() */
public MyserverletTestyuanchuang() {
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 username=request.getParameter("username");
String password=request.getParameter("password");
username=Encoding.encoding(username);//编码转换
String s="获得的用户名为:"+username+":"+password+"";
System.out.println(s);
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);
}
}
3、HttpdoGet方法
首先是建立连接即 new url
再转换成 HttpURLConnection,此处注意导包问题,可能出错
然后设置连接超时与读超时,设置request方法为“GET”
再获得回应,答复
判断http状态来回复先读入,再在屏幕输出
package com.augtwleve;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.awt.event.ActionEvent;
public class Httpdoget extends JFrame {
private JPanel contentPane;
/** * Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Httpdoget frame = new Httpdoget();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public Httpdoget() {
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 arg0) {
String urlString="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang?username=zhangsan&password=123456";
try {
URL url=new URL(urlString);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setRequestMethod("GET");
int code=connection.getResponseCode();
if(code==connection.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();
}
}
});
btnNewButton.setBounds(146, 101, 93, 23);
contentPane.add(btnNewButton);
}
}
4、HttpdoPost方法
首先是建立连接即 new url
再转换成 HttpURLConnection,此处注意导包问题,可能出错
然后设置连接超时与读超时,设置编码转换,
设置url输出为true,设置不适用缓冲(catche)
设置request方法为“POST”
执行输出语句,注意,此处必须先输出,将s字符串发给服务器,才能获得服务器的回应
再获得回应,答复
判断http状态来回复先读入,再在屏幕输出
package com.augtwleve;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.awt.event.ActionEvent;
public class Httpdopost extends JFrame {
private JPanel contentPane;
/** * Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Httpdopost frame = new Httpdopost();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public Httpdopost() {
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 arg0) {
String urlString="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang";
URL url;
try {
url = new URL(urlString);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
//为防止乱码进行编码转换
connection.setRequestProperty("Accept-Charset", "utf-8");
// 设置可以接受序列化的java对象
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//URL连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
connection.setDoOutput(true);
connection.setUseCaches(false);
String s="username=zhangsan&password=123456";
connection.setRequestMethod("POST");
connection.getOutputStream().write(s.getBytes());//将字符串s发给服务器,有服务器的request接收
int code=connection.getResponseCode();//注意不是hashcode()
//注意是connection.HTTP_OK
if(code==connection.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();
}
}
});
btnNewButton.setBounds(114, 79, 93, 23);
contentPane.add(btnNewButton);
}
}
package com.augtwleve;
import java.io.UnsupportedEncodingException;
public class Encoding {
public static String encoding(String s){
if(s==null){
return null;
}
try {
byte[] by=s.getBytes("ISO-8859-1");
s=new String(by,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
}
二、加载数据库
1、serverlet代码
package com.augtwleve;
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;
/** * Servlet implementation class MyserverletTestyuanchuang */
@WebServlet("/MyserverletTestyuanchuang")
public class MyserverletTestyuanchuang extends HttpServlet {
private static final long serialVersionUID = 1L;
/** * @see HttpServlet#HttpServlet() */
public MyserverletTestyuanchuang() {
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 username=request.getParameter("username");
String password=request.getParameter("password");
username=Encoding.encoding(username);//编码转换
Connection connection=Mysqlmanager.newInstance().getConnection();//注意导包
String sql="selection * from user where user_name=? and passerword=?";
String s1="";
try {
PreparedStatement prestate=connection.prepareStatement(sql);//注意导包
prestate.setString(1, username);
prestate.setString(2, password);
ResultSet set=prestate.executeQuery();
set.last();
int num=set.getRow();
if(num==1){
System.out.println("登录成功");
s1="登录成功";
}else{
System.out.println("登录失败");
s1="登录失败";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s="获得的用户名为:"+username+":"+password+"";
response.setHeader("Content-type","text/html;charset=UTF-8");
System.out.println(s);
response.getWriter().append(s);
response.getWriter().append(s1);
}
/** * @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);
}
}
2、数据库代码
package com.augtwleve;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.sun.swing.internal.plaf.synth.resources.synth_zh_CN;
public class Mysqlmanager {
private Connection connection;//私有化
//get connection方法
public Connection getConnection() {
return connection;
}
//单例设计
private static Mysqlmanager manager;
public static synchronized Mysqlmanager newInstance(){
if(manager==null){
manager=new Mysqlmanager();
}
return manager;
}
//在构造器中进行初始化
public Mysqlmanager(){
//注意这是要记得导入mysql的jar包
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);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}