我在上一篇文章中介紹了 使用Get方式提交數據到Tomcat服務器,這篇將介紹使用Post方式提交數據到服務器,由于Post的方式和Get方式創建Web工程是一模一樣的,只用幾個地方的代碼不同所以,我就直接介紹不同的地方,第一個不同點是,提交方式不同,所以修改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方式向服務器提交數據 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } //使用Post方式向服務器提交數據 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取從瀏覽器中發送過來的用戶名 String username = request.getParameter("username"); //獲取從客戶端發送過來的密碼 String password = request.getParameter("password"); //使用iso8859-1編碼將username轉換成字節數組 //再使用utf-8把字節數組轉換成字符串 username = new String(username.getBytes("iso8859-1"), "utf-8"); //在控制臺中打印用戶名和密碼 System.out.println("username=" + username); System.out.println("password=" + password); //獲得一個輸出流 OutputStream os = response.getOutputStream(); //如果用戶名和密碼都輸入正確 if("小志".equals(username) && "123".equals(password)) { //將字符發送至瀏覽器中 os.write("登錄成功".getBytes("utf-8")); } else { //將字符串發送到瀏覽器中 os.write("登錄失敗".getBytes("utf-8")); } } }第二個需要修改的地方是index.jsp,將index.jsp中的代碼修改成下面的代碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="servlet/LoginServlet" method="post"> 用戶名:<input type="text" name="username"><br> 密碼:<input type="password" name="password"><br> <input type="submit" value="提交"> </form> </body> </html>
修改完成后將項目部署到Tomcat服務器上,部署方式可以參考我的博客使用Get方式提交數據到Tomcat服務器
部署完成后在瀏覽器中輸入http://192.168.1.102:8080/WebProject/index.jsp,當瀏覽器中顯示下圖所示的界面表示項目成功的部署到了瀏覽器上

在用戶名中輸入小志,在密碼中輸入123,當瀏覽器中顯示登錄成功時表示登錄成功,因為我在服務器中設置的正確的用戶名是小志,正確的密碼是123

當在用戶名或者密碼中有一項輸入錯誤時會顯示登錄失敗

關于使用Post方式提交數據到Tomcat服務器的方法就給大家介紹這么多,希望對大家有所幫助!
新聞熱點
疑難解答