尚学堂马士兵servlet/JSP笔记(三、Cookie、Session、Application和数据库处理)

来源:互联网 发布:windows路由表 编辑:程序博客网 时间:2024/04/29 18:20


目录(?)[+]

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的信息:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3. import java.util.Date;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9. import javax.servlet.http.HttpSession;  
  10.   
  11.   
  12. public class SessionInfo extends HttpServlet {  
  13.   
  14.     @Override  
  15.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  16.             throws ServletException, IOException {  
  17.         HttpSession mysession = req.getSession(true);  
  18.           
  19.         resp.setContentType("text/html");  
  20.         PrintWriter pw = resp.getWriter();  
  21.         pw.print("<html><head>");  
  22.         pw.print("<title>Session Info</title>");  
  23.         pw.print("</head><body>");  
  24.         pw.print("<h2>Session Information</h2>");  
  25.         pw.print("New Session: " + mysession.isNew());  
  26.         pw.print("<br />SessionID:" + mysession.getId());  
  27.         pw.print("<br />Session created time:" + new Date(mysession.getCreationTime()));  
  28.         pw.print("<br />Session last access time:" + new Date(mysession.getLastAccessedTime()));  
  29.         pw.print("<h2>Request Information</h2>");  
  30.         pw.print("<br />SessionID from request:" + req.getRequestedSessionId());  
  31.         pw.print("<br />SessionID via cookie:" + req.isRequestedSessionIdFromCookie());  
  32.         pw.print("<br /> SessionID via rewrite URL" + req.isRequestedSessionIdFromURL());  
  33.         pw.print("<br /> Valid Session" + req.isRequestedSessionIdValid());  
  34.           
  35.         pw.print("<br /> <a href = 'SessionInfo'>refresh</a>");  
  36. //      重写url  encodeURL括号里面写的是类名。
  37.         pw.print("<br /> <a href =" + resp.encodeURL("SessionInfo") +">refresh</a>");  
  38.         pw.print("</body></html>");  
  39.     }  
  40.   
  41. }  

三、Session示例代码解析


tomcat中的通用session过期时间设置为:conf-->web.xml里面的<session-config>里面的<session-timeout>(时间单位为分钟)。

[html] view plaincopy
  1. <session-config>  
  2.     <session-timeout>30</session-timeout>  
  3. </session-config>  

四、Session的作用及示例

作用:session里面可以存任何你想要存放的内容,使用setAttribute(String name,Object value)设置session里的内容,用getAttribute(String name)获取Session里的内容

示例代码:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3.   
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.HttpServlet;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8. import javax.servlet.http.HttpSession;  
  9.   
  10.   
  11. public class ShowSession extends HttpServlet {  
  12.   
  13.     @Override  
  14.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  15.             throws ServletException, IOException {  
  16.         HttpSession session = req.getSession(true);  
  17.         String head;  
  18.           
  19.         resp.setContentType("text/html");  
  20.         PrintWriter pw = resp.getWriter();  
  21.           
  22.         Integer count = (Integer) session.getAttribute("access");  
  23.           
  24.         if(count == null) {  
  25.             count = new Integer(0);  
  26.             head = "hi,newcommer!";  
  27.         }else {  
  28.             count = new Integer(count.intValue() + 1);  
  29.             head = "welcome back";  
  30.         }  
  31.         session.setAttribute("access", count);  
  32.         pw.print("<html><body><h2>"+ head +"</h2>" +  
  33.                 count +  
  34.                 "</body></html>");  
  35.     }  
  36.   
  37. }  

五、Session总结

1.服务器的一块内存(存key-value)
2.和客户端窗口对应(子窗口)(独一无二)
3.客户端和服务器有对应的SessionID
4.客户端向服务器端发送SessionID的时候两种方式:
    cookie(内存cookie)
    rewriten URL
5.浏览器禁掉cookie,就不能使用session(使用cookie实现的session)
6.如果想安全的使用session(不论客户端是否禁止cookie),只能使用URL重写(大大增加编程负担),所以很多网站要求客户端打开cookie
7.session不像cookie一样,拥有路径访问问题,同一个Application下servlet/JSP,可以共享同一个session,前提是同一个客户端窗口。

application:

用于保存整个WebApplication的声明周期内都可以访问的数据

在API中表现为ServletContext

通过HttpServlet的getServletContext方法可以拿到

通过ServletContext的get/setAttribute方法取得和设置(用法跟session有点类似)

如果把包也拷过去,那么在web.xml中配置。



用法示例:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3.   
  4. import javax.servlet.ServletContext;  
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10.   
  11. public class TestServletContext extends HttpServlet {  
  12.   
  13.     @Override  
  14.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  15.             throws ServletException, IOException {  
  16.         ServletContext context = req.getServletContext();  
  17.                   
  18.         resp.setContentType("text/html");  
  19.         PrintWriter pw = resp.getWriter();  
  20.           
  21.         Integer count = (Integer) context.getAttribute("access");  
  22.           
  23.         if(count == null) {  
  24.             count = new Integer(0);  
  25.         }else {  
  26.             count = new Integer(count.intValue() + 1);  
  27.         }  
  28.         context.setAttribute("access", count);  
  29.         pw.print("<html><body>" +  
  30.                 count +  
  31.                 "</body></html>");  
  32.     }  
  33.   
  34. }   

数据库处理_1:

1.JavaBean 的概念

广义的bean:普通的java类;    狭义的bean:符合sun JavaBean标准的类:属性私有,首字母小写,具有getters和setters,具有一个参数为空的构造方法,具有GUI表现,必须放在包里面(不能使用裸体类),用来实现某一业务逻辑或者取得特定结果。


使用bean连接数据库代码示例:

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3. import java.sql.*;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10.   
  11. public class ShowRs extends HttpServlet {  
  12.   
  13.     @Override  
  14.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  15.             throws ServletException, IOException {  
  16.         Connection conn = null;  
  17.         Statement stmt = null;  
  18.         ResultSet rs = null;  
  19.           
  20.         resp.setContentType("text/html");  
  21.         PrintWriter pw = resp.getWriter();  
  22.           
  23.         pw.print("<head><title>显示数据</title></head><body>" +  
  24.                 "<table border='1' cellspacing='6'><tr><td>ID</td>" +  
  25.                 "<td>title</td></tr>");  
  26.           
  27.         try {  
  28.             Class.forName("com.mysql.jdbc.Driver");  
  29.             conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs?user=root&password=root");  
  30.             stmt = conn.createStatement();  
  31.             rs = stmt.executeQuery("select * from article");  
  32.             while(rs.next()) {  
  33.                 pw.print("<tr><td>"+ rs.getInt(1)+"</td><td>"+ rs.getString("title")+"</td></tr>");  
  34.             }  
  35.               
  36.         } catch (ClassNotFoundException e) {  
  37.             e.printStackTrace();  
  38.         } catch (SQLException e) {  
  39.             e.printStackTrace();  
  40.         } finally {  
  41.             if(rs != null) {  
  42.                 try {  
  43.                     rs.close();  
  44.                 } catch (SQLException e) {  
  45.                     // TODO Auto-generated catch block  
  46.                     e.printStackTrace();  
  47.                 }  
  48.                 rs = null;  
  49.             }  
  50.               
  51.             if(stmt != null) {  
  52.                 try {  
  53.                     stmt.close();  
  54.                 } catch (SQLException e) {  
  55.                     // TODO Auto-generated catch block  
  56.                     e.printStackTrace();  
  57.                 }  
  58.                 stmt = null;  
  59.             }  
  60.               
  61.             if(conn != null) {  
  62.                 try {  
  63.                     conn.close();  
  64.                 } catch (SQLException e) {  
  65.                     // TODO Auto-generated catch block  
  66.                     e.printStackTrace();  
  67.                 }  
  68.                 conn = null;  
  69.             }  
  70.         }  
  71.           
  72.         pw.print("</table></body></html>");  
  73.     }  
  74.   
  75.     @Override  
  76.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  77.             throws ServletException, IOException {  
  78.     }  
  79.   
  80. }  

使用bean连接数据库代码示例:

[java] view plaincopy
  1. import java.sql.*;  
  2.   
  3. public class DB {  
  4.   
  5.     static Connection conn = null;  
  6.       
  7.     public static Connection getConnection() {  
  8.         try {  
  9.             Class.forName("com.mysql.jdbc.Driver");  
  10.             conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs?user=root&password=root");  
  11.         } catch (ClassNotFoundException e) {  
  12.             e.printStackTrace();  
  13.         } catch (SQLException e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.         return conn;  
  17.     }  
  18.       
  19.     public static Statement getStatement(Connection conn) {  
  20.         Statement stmt = null;  
  21.         try {  
  22.             if(conn != null)  
  23.             stmt = conn.createStatement();  
  24.         } catch (SQLException e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.         return stmt;  
  28.     }  
  29.       
  30.     public static ResultSet getResultSet(Statement stmt,String sql) {  
  31.         ResultSet rs = null;  
  32.           
  33.         try {  
  34.             if(stmt != null)  
  35.             rs = stmt.executeQuery(sql);  
  36.         } catch (SQLException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.           
  40.         return rs;  
  41.     }  
  42.       
  43.     public static void colseConnection(Connection conn) {  
  44.         if(conn != null) {  
  45.             try {  
  46.                 conn.close();  
  47.             } catch (SQLException e) {  
  48.                 e.printStackTrace();  
  49.             }  
  50.             conn = null;  
  51.         }  
  52.     }  
  53.       
  54.     public static void closeStatement(Statement stmt) {  
  55.         if (stmt != null) {  
  56.             try {  
  57.                 stmt.close();  
  58.             } catch (SQLException e) {  
  59.                 e.printStackTrace();  
  60.             }  
  61.             stmt = null;  
  62.         }  
  63.     }  
  64.       
  65.     public static void closeRS(ResultSet rs) {  
  66.         if(rs != null) {  
  67.             try {  
  68.                 rs.close();  
  69.             } catch (SQLException e) {  
  70.                 e.printStackTrace();  
  71.             }  
  72.             rs = null;  
  73.         }  
  74.     }  
  75.       
  76. }  

[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3. import java.sql.*;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10.   
  11. public class ShowRsUseBean extends HttpServlet {  
  12.   
  13.     @Override  
  14.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  15.             throws ServletException, IOException {  
  16.         resp.setContentType("text/html");  
  17.         PrintWriter pw = resp.getWriter();  
  18.           
  19.         pw.print("<head><title>显示数据</title></head><body>" +  
  20.                 "<table border='1' cellspacing='6'><tr><td>ID</td>" +  
  21.                 "<td>title</td></tr>");  
  22.           
  23.         Connection conn = DB.getConnection();  
  24.         Statement stmt = DB.getStatement(conn);  
  25.         ResultSet rs = DB.getResultSet(stmt, "select * from article");  
  26.           
  27.         try {  
  28.             while (rs.next()) {  
  29.                 pw.print("<tr><td>"+ rs.getInt(1)+"</td><td>"+ rs.getString("title")+"</td></tr>");  
  30.             }  
  31.         } catch (SQLException e) {  
  32.             e.printStackTrace();  
  33.         } finally {  
  34.           
  35.             DB.closeRS(rs);  
  36.             DB.closeStatement(stmt);  
  37.             DB.colseConnection(conn);  
  38.         }  
  39.         pw.print("</table></body></html>");  
  40.           
  41.     }  
  42.   
  43. }  

0 0
原创粉丝点击