尚学堂马士兵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>");
		
	}

}




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