尚學堂馬士兵servlet/JSP筆記(三、Cookie、Session、Application和數據庫處理)

Cookie:

一、Cookie的概念

1.服務器可以向客戶端寫內容
2.只能是文本內容
3.客戶端可以阻止服務器寫入
4.只能拿自己WebApp寫入的內容
5.Cookie分爲兩種:a.屬於窗口/子窗口的;b.屬於文本的。
6.一個servlet/jsp設置的cookie能夠被同一路徑下面或者子路徑下面的servlet/jsp讀到(路徑=URL)(路徑 !=真實文件路徑)

二、創建Cookie的示例代碼

創建cookie的代碼:
cookie = new Cookie("cookie_name","cookie_value");
cookie.setMaxAge(3600);//不設置的話,cookie寫在內存裏,窗口關閉,該cookie就失效了。
resp.addCookie(cookie);

拿到cookie的代碼:
Cookie[] cookies = req.getCookies();
cookies[0].getName();
cookies[0].getValue();

三、Cookie路徑試驗

<url-pattern>/servlet/TestCookies</url-pattern>    //設置cookie
<url-pattern>/servlet/ShowCookies</url-pattern> //拿cookie,可以拿到

<url-pattern>/TestCookies</url-pattern>    //設置cookie
<url-pattern>/servlet/ShowCookies</url-pattern> //拿cookie,可以拿到

<url-pattern>/servlet/TestCookies</url-pattern>    //設置cookie
<url-pattern>/ShowCookies</url-pattern> //拿cookie,不可以拿到

Session:

一、Session的概念和規則

Session是記錄在服務器端的,並且把session-id寫在臨時cookie中。
在某段時間一連串客戶端與服務器端的“交易”
在jsp/servlet中如果瀏覽器不支持cookie,可以通過URL重寫來實現,就是將一些額外數據追加到表示會話的每個URL末尾,服務器在該標示符與其存儲的有關的該會話的數據之間建立關聯。
可以通過程序來終止一個會話。如果客戶端在一定時間內沒有操作,服務器會自動終止會話。
通過HttpSession來讀寫Session(地址欄傳送Session)

規則:
如果瀏覽器支持Cookie,創建Session的時候把SessionID保存在Cookie裏
如果不支持,必須自己編程使用URL重寫的方式實現Session
    response.encodeURL()
        轉碼
        URL後面加入SessionID
Session不像Cookie擁有路徑訪問的問題
    同一個application下的servlet/jsp可以共享同一個session,前提是同一個客戶端窗口。

二、Session使用演示

Session的信息:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class SessionInfo extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession mysession = req.getSession(true);
		
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		pw.print("<html><head>");
		pw.print("<title>Session Info</title>");
		pw.print("</head><body>");
		pw.print("<h2>Session Information</h2>");
		pw.print("New Session: " + mysession.isNew());
		pw.print("<br />SessionID:" + mysession.getId());
		pw.print("<br />Session created time:" + new Date(mysession.getCreationTime()));
		pw.print("<br />Session last access time:" + new Date(mysession.getLastAccessedTime()));
		pw.print("<h2>Request Information</h2>");
		pw.print("<br />SessionID from request:" + req.getRequestedSessionId());
		pw.print("<br />SessionID via cookie:" + req.isRequestedSessionIdFromCookie());
		pw.print("<br /> SessionID via rewrite URL" + req.isRequestedSessionIdFromURL());
		pw.print("<br /> Valid Session" + req.isRequestedSessionIdValid());
		
		pw.print("<br /> <a href = 'SessionInfo'>refresh</a>");
//		重寫url
		pw.print("<br /> <a href =" + resp.encodeURL("SessionInfo") +">refresh</a>");
		pw.print("</body></html>");
	}

}

三、Session示例代碼解析


tomcat中的通用session過期時間設置爲:conf-->web.xml裏面的<session-config>裏面的<session-timeout>(時間單位爲分鐘)。

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

四、Session的作用及示例

作用:session裏面可以存任何你想要存放的內容,使用setAttribute(String name,Object value)設置session裏的內容,用getAttribute(String name)獲取Session裏的內容

示例代碼:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class ShowSession extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession(true);
		String head;
		
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		
		Integer count = (Integer) session.getAttribute("access");
		
		if(count == null) {
			count = new Integer(0);
			head = "hi,newcommer!";
		}else {
			count = new Integer(count.intValue() + 1);
			head = "welcome back";
		}
		session.setAttribute("access", count);
		pw.print("<html><body><h2>"+ head +"</h2>" +
				count +
				"</body></html>");
	}

}

五、Session總結

1.服務器的一塊內存(存key-value)
2.和客戶端窗口對應(子窗口)(獨一無二)
3.客戶端和服務器有對應的SessionID
4.客戶端向服務器端發送SessionID的時候兩種方式:
    cookie(內存cookie)
    rewriten URL
5.瀏覽器禁掉cookie,就不能使用session(使用cookie實現的session)
6.如果想安全的使用session(不論客戶端是否禁止cookie),只能使用URL重寫(大大增加編程負擔),所以很多網站要求客戶端打開cookie

application:

用於保存整個WebApplication的聲明週期內都可以訪問的數據

在API中表現爲ServletContext

通過HttpServlet的getServletContext方法可以拿到

通過ServletContext的get/setAttribute方法取得和設置(用法跟session有點類似)


用法示例:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TestServletContext extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ServletContext context = req.getServletContext();
				
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		
		Integer count = (Integer) context.getAttribute("access");
		
		if(count == null) {
			count = new Integer(0);
		}else {
			count = new Integer(count.intValue() + 1);
		}
		context.setAttribute("access", count);
		pw.print("<html><body>" +
				count +
				"</body></html>");
	}

} 

數據庫處理_1:

1.JavaBean 的概念

廣義的bean:普通的java類;    狹義的bean:符合sun JavaBean標準的類:屬性私有,首字母小寫,具有getters和setters,具有一個參數爲空的構造方法,具有GUI表現,必須放在包裏面(不能使用裸體類),用來實現某一業務邏輯或者取得特定結果。


使用bean連接數據庫代碼示例:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ShowRs extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		
		pw.print("<head><title>顯示數據</title></head><body>" +
				"<table border='1' cellspacing='6'><tr><td>ID</td>" +
				"<td>title</td></tr>");
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs?user=root&password=root");
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from article");
			while(rs.next()) {
				pw.print("<tr><td>"+ rs.getInt(1)+"</td><td>"+ rs.getString("title")+"</td></tr>");
			}
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				rs = null;
			}
			
			if(stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				stmt = null;
			}
			
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				conn = null;
			}
		}
		
		pw.print("</table></body></html>");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}

}

使用bean連接數據庫代碼示例:

import java.sql.*;

public class DB {

	static Connection conn = null;
	
	public static Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs?user=root&password=root");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static Statement getStatement(Connection conn) {
		Statement stmt = null;
		try {
			if(conn != null)
			stmt = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	
	public static ResultSet getResultSet(Statement stmt,String sql) {
		ResultSet rs = null;
		
		try {
			if(stmt != null)
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return rs;
	}
	
	public static void colseConnection(Connection conn) {
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}
	
	public static void closeStatement(Statement stmt) {
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			stmt = null;
		}
	}
	
	public static void closeRS(ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}
	}
	
}

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ShowRsUseBean extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		
		pw.print("<head><title>顯示數據</title></head><body>" +
				"<table border='1' cellspacing='6'><tr><td>ID</td>" +
				"<td>title</td></tr>");
		
		Connection conn = DB.getConnection();
		Statement stmt = DB.getStatement(conn);
		ResultSet rs = DB.getResultSet(stmt, "select * from article");
		
		try {
			while (rs.next()) {
				pw.print("<tr><td>"+ rs.getInt(1)+"</td><td>"+ rs.getString("title")+"</td></tr>");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
		
			DB.closeRS(rs);
			DB.closeStatement(stmt);
			DB.colseConnection(conn);
		}
		pw.print("</table></body></html>");
		
	}

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章