前面的博客中介紹的都是從服務器中獲取數據,這篇博客將介紹向服務器發送數據,並且服務器將數據的處理結果返回給客戶端,這次先介紹使用Get方式向服務器發送數據,下一篇博客將介紹使用Post方式向服務器發送數據,
實現方式:
第一步:使用MyEclipse創建一個Web project,項目命名爲WebProject->在src文件夾中新建一個包名爲com.fyt.org的包
->在包中新建一個Servlet,Servlet命名爲LoginServlet,並在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 {
//獲取從瀏覽器中發送過來的用戶名
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"));
}
}
//使用Post方式向服務器提交數據
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
第二步:啓動Tomcat服務器,Tomcat服務器的啓動方式可以參考我的博客在MyEclipse上部署Tomcat服務器
第三步:修改WebProject項目中的WebRoot目錄下的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="get">
用戶名:<input type="text" name="username"><br>
密碼:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
第四步:將項目部署到Tomcat服務器上,部署方式如下
1、點擊下圖中圈出的圖標
2、Project中選擇WebProject,並且單擊Add按鈕
3、Server中選擇Tomcat 7.x,並且單擊finish按鈕
4、單擊OK按鈕,此時WebProject項目已經成功的部署到了Tomcat服務器上
第五步:打開瀏覽器,在瀏覽器中輸入http://192.168.1.102:8080/WebProject/index.jsp,在瀏覽器中顯示了下圖所示的界面表示成功的訪問到了服務器中的數據
在用戶名中輸入小志,在密碼中輸入123,單擊登錄按鈕後,彈出了登錄成功界面後表示登錄成功了,因爲設置的正確的用戶名是小志,正確的密碼是123
當在用戶名和密碼中輸入錯誤的密碼後,會提示登錄失敗