1. 程式人生 > >完整JavaWeb專案筆記 第六部分-核心Servlet主處理實現

完整JavaWeb專案筆記 第六部分-核心Servlet主處理實現

文章目錄

一 主處理邏輯做什麼

  其實在第五部分已經把IServlet的整體設計做的差不多了,但是process()並沒有實現,process()就是我所謂的主處理方法。

  這個方法要做幾件事情:

  1. 請求處理耗時統計
  2. 分發請求到具體處理方法
  3. 拼裝IResponse應答結構
  4. 解決跨域處理

  所以先定義方法如下:

private void process(
) throws IOException { try { processAction(); } catch (Throwable t) { } }

二 補充處理耗時

  請求到來時即應記錄下當前的系統時間,並且在請求處理完畢後再次計下當前的系統時間,然後取前後時間的跨度值作為請求耗時。

  注意,每一個請求的應答為IResponse型別,且IServlet在請求進入時已經例項化好了IResponse物件result,所以補充邏輯如下:

private void process() throws IOException
{
		long StartTime =
System.currentTimeMillis(); try { processAction(); } catch (Throwable t) { } result.setElapsedTime((int) (System.currentTimeMillis() - StartTime)); }

三 拼裝IResponse並響應請求

  這時候就用上了我們之前的準備工作,GsonUtil完美的支援我們現在工作需求:

private void process() throws IOException
{
		long StartTime =
System.currentTimeMillis(); try { processAction(); } catch (Throwable t) { } result.setElapsedTime((int) (System.currentTimeMillis() - StartTime)); response.setContentType("text/plain; charset=UTF-8"); Gson gson = GsonUtil.getGson(); try { PrintWriter out = response.getWriter(); response.getWriter().print(gson.toJson(result)); out.flush(); out.close(); } catch (Exception e) { } }

四 解決跨域問題

  要解決跨域問題,首先要知道跨域問題時怎麼來的,比如說在a.com下去訪問b.com的資源,這就是跨域。瀏覽器允許跨域寫,但是不允許跨域讀。這裡說的寫是指請求,讀則為應答。

  瞭解其原理之後,我們的解決方案為在應答時處理跨域問題,所以補充處理邏輯如下:

private void process() throws IOException
{
		long StartTime = System.currentTimeMillis();
		
		try
		{
			processAction();
		}
		catch (Throwable t)
		{
		}
		
		result.setElapsedTime((int) (System.currentTimeMillis() - StartTime));
		response.setContentType("text/plain; charset=UTF-8");
		Gson gson = GsonUtil.getGson();
		
		try
		{
			PrintWriter out = response.getWriter();
			String callback = request.getParameter("callback");

			if (callback == null)
			{
				response.addHeader("Access-Control-Allow-origin", request.getHeader("callback"));
				response.addHeader("Access-Control-Allow-Methods", "POST,GET");
				// 是否支援cookie跨域
				response.addHeader("Access-Control-Allow-Credentials", "true"); 
				response.getWriter().print(gson.toJson(result));
			}
			else
			{
				String output = callback + "(" + gson.toJson(result) + ")";
				response.getWriter().print(output);
			}

			out.flush();
			out.close();
		}
		catch (Exception e)
		{
		}
}