Servlet中接收和返回數據



public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override public void init() throws ServletException { System.out.println("進入 服務器..."); } }

  

我們可以看到HttpServletRequest, HttpServletResponse這兩個對象。可以說,這是JavaWeb中至關重要的兩個對象。接下來,我們來做一個簡短的說明:

1、HttpServletRequest

request對象(HttpServletRequest)代表客戶端的請求,當客戶端通過HTTP協議訪問服務器
時,HTTP請求頭中的所有信息都封裝在這個對象中,通過這個對象提供的方法,可以獲得客戶端請求的所有信息。

其中,請求頭就是Request Headers. 我們還可以看到請求的方式是Get方式,通過瀏覽器地址欄的方式就是GET方式。現在,我們改變在請求的同時加入一點信息:

http://localhost/wzry/login.do?username=admin&password=123&type=weixin


在請求地址后面加一個 ?,開始拼接數據,每一個數據都是key=value 的形式,不同數據之間用 & 連接。再次回車。我們可以看到信息發生了變化:

不論你是什么請求,你往服務器傳遞的數據只能是 字符串!

現在,我們可以在Servlet中接收這些參數!

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username=req.getParameter("username");
		String password=req.getParameter("password");
		String type=req.getParameter("type");
		System.out.println("用戶登錄...");
		System.out.println(username);
		System.out.println(password);
		System.out.println(type);
		
	}

  

運行結果:

 

正常情況下,為了保存這些數據,我們都會各自建立一個Java類,比如用戶類。我們為了方便起見,可以采用一種公用的數據結構來保存,那就是Map。從道理上也能明白吧,客戶端傳遞數據到我們的服務器,我們是不是首先得想辦法把它存起來?好像給你一筐雞蛋,然后他說,雞蛋給你,框子我得拿走,那么你是不是得找一個容器,把雞蛋裝起來呢?不就是這個道理嘛。

Map就是這么一個容器。
修改后的代碼:

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String type = req.getParameter("type");
		System.out.println("用戶登錄...");
		
		System.out.println(username);
		System.out.println(password);
		System.out.println(type);
		
		System.out.println("開始存入map...");
		Map<String,Object> map=new HashMap<>();
		map.put("username", username);
		map.put("password", password);
		map.put("type", type);
		System.out.println("存入map成功!");
		System.out.println(map);
	}

  

在實際的開發中,傳進來的數據肯定是不一樣的,如果我們太依賴於getParameter這個方法,就無法做到靈活變通。那么有沒有一種通用的方法,讓request對象中附帶的數據自動轉換為Map呢?

我已經封裝好了一個工具類,里面就有這樣的方法。

public static Map<String,Object> getParameters(HttpServletRequest req){
		Map<String,Object> map=new HashMap<>();
		Enumeration<String> names = req.getParameterNames();
		while (names.hasMoreElements()) {
			String key=names.nextElement();	//獲取key值
			map.put(key, req.getParameter(key));	//獲取value值
		}
		return map;
	}

  

於是請求參數的獲取就變得很簡單了

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("用戶登錄...");
		System.out.println("開始存入map...");
		Map<String,Object> map=StringUtils.getParameters(req);
		System.out.println("存入map成功!");
		System.out.println(map);
	}

  

2、HttpServletResponse

Web服務器收到客戶端的http請求,會針對每一次請求,分別創建一個用於代表請求的request對象(HttpServletRequest)、和代表響應的response對象(HttpServletResponse)。
request和response對象即代表請求和響應,那我們要獲取客戶機提交過來的數據,只需要找request對象就行了。要向客戶機輸出數據,只需要找response對象就行了。

在剛才的例子中,我們添加以下代碼:

		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		writer.println("登錄成功!");

  頁面效果:

 

我們通過這種方式,就可以往客戶端發送一個數據。

剛才講了GET方式提交可以直接在瀏覽器地址欄操作,GET方式提交的缺點就是會暴露自己的數據信息,還有一種POST提交的方式。相比GET方式要安全一點,它不會直接暴露數據。現在我們通過form表單來做一個講解。
在WebContent目錄下新建一個index.jsp。

編寫form表單:

	<!-- post提交表單 -->
	<form action="login.do" name="myform" method="post" onsubmit="check();">
		<table>
			<tr>
				<td>用戶名:</td>
				<td><input type="text" name="username" id="username" /></td>
			</tr>
			<tr>
				<td>密碼:</td>
				<td><input type="password" name="password" id="password" /></td>
			</tr>
		</table>
		<input type="submit" value="提交"/>
		<input type="hidden" name="type" value="weixin" />
	</form>

  

我們一般還需要在后台進行一個驗證。

我們故意不填寫用戶名和密碼,點擊登錄按鈕,結果並沒有什么卵用。因為其實傳遞到后台是有值的,只是為””,這一點和js不同,在Java中,””不等於假,它只是代表一個空字符串。所以我們需要修改一下驗證條件。還有,為了不讓代碼繼續往下執行,我們需要及時return。

 

 為了給用戶返回錯誤信息,我們得把信息拋到頁面上。

 

關注一下,這里有兩個重復點,於是考慮封裝。

/**
 * 工具類
 * @author Administrator
 *
 */
public class StringUtils {
	/**
	 * 是否為空
	 * @param o
	 * @return
	 */
	public static boolean isEmpty(Object o){
		if(o==null)return true;
		if("".equals(o))return true;
		return false;
	}
	
	/**
	 * 不為空
	 * @param o
	 * @return
	 */
	public static boolean isNotEmpty(Object o){
		return !isEmpty(o);
	}
	
	/**
	 * 輸出信息到頁面
	 * @param resp
	 * @param o
	 */
	public static void writeObject(HttpServletResponse resp,Object o){
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer=null;
		try {
			writer= resp.getWriter();
			writer.println(o);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 獲取請求參數
	 * @param req
	 * @return
	 */
	public static Map<String,Object> getParameters(HttpServletRequest req){
		Map<String,Object> map=new HashMap<>();
		Enumeration<String> names = req.getParameterNames();
		while (names.hasMoreElements()) {
			String key=names.nextElement();	//獲取key值
			map.put(key, req.getParameter(key));	//獲取value值
		}
		return map;
	}
}

  

封裝之后代碼簡潔很多了

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("用戶登錄...");
		System.out.println("開始存入map...");
		Map<String,Object> map=StringUtils.getParameters(req);
		System.out.println("存入map成功!");
		System.out.println(map);
		
		if(StringUtils.isEmpty(map.get("username"))){
			StringUtils.writeObject(resp,"用戶名不能為空!");
			System.out.println("用戶名不能為空!");
			return;
		}
		if(StringUtils.isEmpty(map.get("password"))){
			StringUtils.writeObject(resp,"密碼不能為空!");
			System.out.println("密碼不能為空!");
			return;
		}
		StringUtils.writeObject(resp,"登錄成功!");
	}

  

 參考:https://www.cnblogs.com/skyblue-li/p/8251225.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM