jsp:實現了靜態html中,插入了動態的代碼
真的好嗎?
答:非常不好(耦合)
------------------------
servlet:動態代碼中,插入靜態html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<font size="7"><%=new java.util.Date() %></font>
</body>
</html>
PrintWriter out = response.getWriter();
out.println();
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
out.println("<html>");
out.println("<head>");
out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
out.println("<title>Insert title here</title>");
out.println("</head>");
out.println("<body>");
//<%=new java.util.Date() %>
out.println("<font size=\"7\">"+new java.util.Date()+"</font>");
//out.println("<font size="7"><%=new java.util.Date() %></font>");
out.println("</body>");
out.println("</html>");
總結:
1. jsp跟servlet沒有本質上在區別。
2. 在jsp中html代碼,例如<html>,會自動變成out.print(“<html>”),這一個過程完全由tomcat替程序員完成。
像out.print(“<html>”)在最早期的網頁編程代碼了cgi,真的這樣寫。
PrintWriter out = response.getWriter();
在Servlet中,out對象其實來自於response對象,那么在jsp中也可以使用
response.getWriter(),但是jsp其實已經內置了out對象。不用寫這行代碼。
4、JSP中一共預先定義了9個這樣的對象,
分別為:request、response、session、application、out、pagecontext、config、page、exception
但是日常基本99.99%只用request、response、out、session
因為http協議是無狀態的,每次訪問后,鏈接都斷開的,所以使用session可以獲得之前鏈接的信息。
Session一般用於:登錄
JSON對象
JSP實現,在html的這個靜態頁面的基礎之上,
實現了跟客戶端交互的動態效果。
交互中,經常使用
- request.getParameter("username"); 接受客戶端發送的內容
- response則用於響應客戶端
作為響應對象,response又分2種響應
- 輸出內容{html,json}
- 跳轉(比如響應一個錯誤登錄頁面)
JSON
- 單個對象{}
- 單個對象中,里面包含多個屬性{"name":"小明","sex":"其它"}
- 多個對象 [{},{},{}],這里是一個對象數組,里面包含3個對象
