servlet-使用dopost方式提交数据(代码示例)
2014-05-16 16:55
453 查看
代码来自:http://blog.csdn.net/neu_yousei/article/details/22486983
客户端代码
服务器端代码
package com.login.manager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginAction extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//客户端 HttpUtils并没有写request方法是post ,但服务器端可自动识别
String method = request.getMethod();
System.out.println("request method :"+method);
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
System.out.println("-username->>"+username);
String password = request.getParameter("password");
System.out.println("-password->>"+password);
if (username.equals("admin") && password.equals("123")) {
// 表示服务器段返回的结果
out.print("login is success !");
} else {
out.print("login is fail !");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
客户端代码
package com.http.post; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class HttpUtils { // 表示服务器端的url private static String PATH = "http://192.168.0.100:8080/myhttp/servlet/LoginAction"; private static URL url; public HttpUtils() { // TODO Auto-generated constructor stub } static { try { url = new URL(PATH); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * params 填写的URL的参数 encode 字节编码 */ public static String sendPostMessage(Map<String, String> params, String encode) { StringBuffer stringBuffer = new StringBuffer(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { try { stringBuffer .append(entry.getKey()) .append("=") .append(URLEncoder.encode(entry.getValue(), encode)) .append("&"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 删掉最后一个 & 字符 stringBuffer.deleteCharAt(stringBuffer.length() - 1); System.out.println("-->>" + stringBuffer.toString()); try { HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true);// 从服务器获取数据 httpURLConnection.setDoOutput(true);// 向服务器写入数据 // 获得上传信息的字节大小及长度 byte[] mydata = stringBuffer.toString().getBytes(); // 设置请求体的类型 httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Lenth", String.valueOf(mydata.length)); // 获得输出流,向服务器输出数据 OutputStream outputStream = (OutputStream) httpURLConnection .getOutputStream(); outputStream.write(mydata); // 获得服务器响应的结果和状态码 int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { // 获得输入流,从服务器端获得数据 InputStream inputStream = (InputStream) httpURLConnection .getInputStream(); return (changeInputStream(inputStream, encode)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ""; } /* * // 把从输入流InputStream按指定编码格式encode变成字符串String */ public static String changeInputStream(InputStream inputStream, String encode) { // ByteArrayOutputStream 一般叫做内存流 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; String result = ""; if (inputStream != null) { try { while ((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } result = new String(byteArrayOutputStream.toByteArray(), encode); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Map<String, String> params = new HashMap<String, String>(); params.put("username", "admin"); params.put("password", "123"); String result = sendPostMessage(params, "utf-8"); System.out.println("-result->>" + result); } }
服务器端代码
package com.login.manager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginAction extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//客户端 HttpUtils并没有写request方法是post ,但服务器端可自动识别
String method = request.getMethod();
System.out.println("request method :"+method);
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
System.out.println("-username->>"+username);
String password = request.getParameter("password");
System.out.println("-password->>"+password);
if (username.equals("admin") && password.equals("123")) {
// 表示服务器段返回的结果
out.print("login is success !");
} else {
out.print("login is fail !");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
相关文章推荐
- JQuery以JSON方式提交数据到服务端示例代码
- JSP中使用AJAX示例:分别将结果提交为STRUTS,SERVLET,WEBWORK的不同操作方式
- JSP中使用AJAX示例:分别将结果提交为STRUTS,SERVLET,WEBWORK的不同操作方式
- [Android开发]Android之使用HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- Android学习笔记46:使用Post方式提交数据
- 使用gfortran将数据写成Grads格式的代码示例
- Ajax使用POST方式异步提交数据
- 使用secondary sort实现数据关联 完整示例代码
- Android学习笔记46-使用Post方式提交数据
- PHP下使用CURL方式POST数据至API接口的代码
- Android普通方式的DoPost请求提交数据
- git使用补丁方式进行软件代码提交
- 在c#中使用HttpWebRequest时的几种提交数据方式学习和分析
- 项目中使用XML方式去取数据插入数据代码
- Android学习之Http使用Post方式进行数据提交
- 使用get,post,httpclient三种方式向服务器提交文本数据
- JSP中Servlet获取表单数据示例(doGet()和doPost()共用接口)
- 使用GET和POST方式将数据提交给服务器
- php中用socket模拟http中post或者get提交数据的示例代码