Servlet中doGet和doPost
doGet 直接连接在URL后面的是显式的,提交到的数据有限
doPost 隐式的,比get安全,提交数据长度不限
#
这两个方法属于HttpURlconnection中的方法
提交的数据时,如果用get方式,可以通过地址栏的历史记录被别人看到。所以在web开发中,表单的提交一般用post方式,而不用get方式。Get方式的一个优点在于,可以很方便地控制链接的目标地址。
如果需要同时实现doGet 和doPost方式的Servlet,通常会只在doGet方法中实现处理过程,二在doPost方法直接调用doGet方法。
主要代码实现如下(需要界面的话,只需将代码写下按钮事件相应下即可):
String urlString="http://localhost:8080/MyServersTest/MyTestServerlet?userName=张三&password=123456";//直接在URL后面的是doget方法
try {
URL url=new URL(urlString);//生成URL
URLConnection connection=url.openConnection();//打开URL连接
//强制造型成HttpURLConnection
HttpURLConnection connection2=(HttpURLConnection) connection;
//设置请求方法
connection2.setRequestMethod("GET");
//网络连接超时
connection2.setConnectTimeout(10000);
//读取时间超时
connection2.setReadTimeout(3000);
//设置编码格式
//设置接收数据类型
connection2.setRequestProperty("Accept-Charset", "UTF-8");
//设置可以接收到的序列化Java对象
connection2.setRequestProperty("content-Type", "application/x-www-form-urlencoded");
int code=connection2.getResponseCode();
if (code==connection2.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(connection2.getInputStream()));
String s=br.readLine();
while (s!=null) {
System.out.println(s);
s=br.readLine();
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch(SocketTimeoutException e1){
System.out.println("网络连接超时");
}catch(ConnectException e1){
System.out.println("请求超时");
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
实现doGet和doPost还需要服务器的启动,服务器端的代码如下:
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 org.apache.tomcat.util.http.fileupload.ParameterParser;
/**
* 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 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");
String s = "";
System.out.println("用户名" + userName + "密码" + password);
userName = Encoding.doEncoding(userName);
Connection connection = SQLManager.newInstabce().getConn();
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) {
s = "登陆成功";
} else {
s = "用户名和密码错误";
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// if (userName==null&&password==null) {
// System.out.println("userName=null password=null");
// }else{
// userName=Encoding.doEncoding(userName);
// System.out.println("提交了用户和密码,用户名:"+userName+" 密码:"+password);
// String s="提交了用户信息,用户名称:"+userName+" 密码:"+password;
// 让浏览器以utf-8编码格式解析
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 {
// TODO Auto-generated method stub
doGet(request, response);
}
}
启动成功后:
启动doGet后,若结果匹配
服务端:
用户名zhangsan密码12345
执行成功
客户端:
登陆成功
下面是doPost方法(用法,位置和doGet方法一样)
String urlString="http://localhost:8080/MyServersTest/MyTestServerlet";
//直接在URL后面的是doPost方法
try {
URL url=new URL(urlString);//生成URL
URLConnection connection=url.openConnection();//打开URL连接
//强制造型成HttpURLConnection
HttpURLConnection connection2=(HttpURLConnection) connection;
//网络连接超时
connection2.setConnectTimeout(3000);
//读取时间超时
connection2.setReadTimeout(3000);
//设置接收数据类型
connection2.setRequestProperty("Accept-Charset", "UTF-8");
//设置可以接收到的序列化Java对象
connection2.setRequestProperty("content-Type", "application/x-www-form-urlencoded");
//设置请求方法
connection2.setRequestMethod("POST");
//connection2.setDoInput(true);//设置是可以读取服务器返回的内容,默认为true
//设置客户端可以给服务器提交素具,默认是false,post方法必须设置为true
connection2.setDoOutput(true);
//post方法不允许使用缓存
connection2.setUseCaches(false);
String params="username=zhangsan&pasword=12345";
connection2.getOutputStream().write(params.getBytes());
int code=connection2.getResponseCode();
System.out.println(code);
if (code==connection2.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(connection2.getInputStream()));
String s=br.readLine();
//System.out.println(s);
while (s!=null) {
System.out.println(s);
s=br.readLine();
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch(SocketTimeoutException e1){
System.out.println("网络连接超时");
}catch(ConnectException e1){
System.out.println("服务器拒绝连接");
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient中的doGet和doPost方法
HTTPURLConnection 是sun封装成的网络连接
HttpClient 是Apache使用httpURLConnection封装的类doGet方法
String urlString="http://localhost:8080/MyServiceTest/MyTestServerlet?username=zhangsan&password=123456";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
//生成client的buidler
HttpClient client=builder.build();//生成client
HttpGet get=new HttpGet(urlString);//设置为get方法
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//设置服务器接收后数据的读取方式为utf8
try {
HttpResponse response=client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含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 (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
doPost方法
String url="http://192.168.0.30:8080/MyServiceTest/MyTestServerlet";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost post=new HttpPost(url);
NameValuePair pair1=new BasicNameValuePair("username", "张三");
NameValuePair pair2=new BasicNameValuePair("password", "123456");
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) {
// 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();
}