java post 提交数据_使用Post方式提交数据到Tomcat服务器的方法
我在上一篇文章中介紹了 使用Get方式提交數(shù)據(jù)到Tomcat服務(wù)器,這篇將介紹使用Post方式提交數(shù)據(jù)到服務(wù)器,由于Post的方式和Get方式創(chuàng)建Web工程是一模一樣的,只用幾個(gè)地方的代碼不同所以,我就直接介紹不同的地方,第一個(gè)不同點(diǎn)是,提交方式不同,所以修改LoginServlet.Java中的代碼
package com.fyt.org;
import java.io.IOException;
import java.io.OutputStream;
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 LoginServlet extends HttpServlet {
public LoginServlet() {
super();
}
public void destroy() {
super.destroy();
}
//使用Get方式向服務(wù)器提交數(shù)據(jù)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
//使用Post方式向服務(wù)器提交數(shù)據(jù)
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取從瀏覽器中發(fā)送過(guò)來(lái)的用戶名
String username = request.getParameter("username");
//獲取從客戶端發(fā)送過(guò)來(lái)的密碼
String password = request.getParameter("password");
//使用iso8859-1編碼將username轉(zhuǎn)換成字節(jié)數(shù)組
//再使用utf-8把字節(jié)數(shù)組轉(zhuǎn)換成字符串
username = new String(username.getBytes("iso8859-1"), "utf-8");
//在控制臺(tái)中打印用戶名和密碼
System.out.println("username=" + username);
System.out.println("password=" + password);
//獲得一個(gè)輸出流
OutputStream os = response.getOutputStream();
//如果用戶名和密碼都輸入正確
if("小志".equals(username) && "123".equals(password)) {
//將字符發(fā)送至瀏覽器中
os.write("登錄成功".getBytes("utf-8"));
}
else {
//將字符串發(fā)送到瀏覽器中
os.write("登錄失敗".getBytes("utf-8"));
}
}
}
第二個(gè)需要修改的地方是index.jsp,將index.jsp中的代碼修改成下面的代碼
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page用戶名:
密碼:
修改完成后將項(xiàng)目部署到Tomcat服務(wù)器上,部署方式可以參考我的博客使用Get方式提交數(shù)據(jù)到Tomcat服務(wù)器
部署完成后在瀏覽器中輸入http://192.168.1.102:8080/WebProject/index.jsp,當(dāng)瀏覽器中顯示下圖所示的界面表示項(xiàng)目成功的部署到了瀏覽器上
在用戶名中輸入小志,在密碼中輸入123,當(dāng)瀏覽器中顯示登錄成功時(shí)表示登錄成功,因?yàn)槲以诜?wù)器中設(shè)置的正確的用戶名是小志,正確的密碼是123
當(dāng)在用戶名或者密碼中有一項(xiàng)輸入錯(cuò)誤時(shí)會(huì)顯示登錄失敗
關(guān)于使用Post方式提交數(shù)據(jù)到Tomcat服務(wù)器的方法就給大家介紹這么多,希望對(duì)大家有所幫助!
總結(jié)
以上是生活随笔為你收集整理的java post 提交数据_使用Post方式提交数据到Tomcat服务器的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 反射 参数名_JAVA 8 反
- 下一篇: java 等比缩放图片_java处理图片