第11天(就业班) servlet编程、读取web应用下的资源文件、cookie、Session技术

来源:互联网 发布:未来城网络黄金 编辑:程序博客网 时间:2024/04/28 05:06

1.课程回顾

Servlet编程
1)Servlet生命周期(重点)
构造方法: 创建servlet对象。默认情况下,第一次访问servlet对象时。只调用1次。
init方法(有参): 创建完servlet对象后调用。只调用1次。
注意: 会调用无参的init方法。
service方法: servlet提供服务的方法。每次发出请求调用。
注意: request对象 ,response对象
destroy方法: tomcat服务器停止或web应用重新部署,servlet对象销毁,destroy方法被调用。
2)ServletConfig对象
获取servlet的初始化参数:
getInitParameter("name");
getInitParameterNames();
3)ServletContext对象
得到web应用路径:
context.getContextPath();
request.getContextPath();  等价于上面的代码
得到web应用参数:
context.getInitParameter("name");
context.getInitParameterNames();
域对象:
context.setAttribute("name",Object): 保存数据
context.getAttribute("name")   得到数据
context.removeAttribue("name")  清除数据
转发
context.getRequestDispatcher("路径").forward(request,response);
request.getRequestDispacher("路径").forward(request,response);  等价于上面的代码
得到web应用中的资源文件
context.getRealPath("路径")

context.getResourceAsStream("路径");

package com.xp.path;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;public class PathDemo extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");//目标资源: target.html/** * 思考: 目标资源是给谁使用的。 * 给服务器使用的:   / 表示在当前web应用的根目录(webRoot下) * 给浏览器使用的: /  表示在webapps的根目录下 *//** * 1.转发 *///request.getRequestDispatcher("/target.html").forward(request, response);/** * 2.请求重定向 *///response.sendRedirect("/day11/target.html");/** * 3.html页面的超连接href */response.getWriter().write("<html><body><a href='/day11/target.html'>超链接</a></body></html>");/** * 4.html页面中的form提交地址 */response.getWriter().write("<html><body><form action='/day11/target.html'><input type='submit'/></form></body></html>");}}

2.读取web应用下的资源文件(例如properties)

package com.xp.resource;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 读取web应用下的资源文件(例如properties) * @author APPle */public class ResourceDemo extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/** *  . 代表java命令运行目录。java运行命令在哪里?? 在tomcat/bin目录下 *   结论: 在web项目中, . 代表在tomcat/bin目录下开始,所以不能使用这种相对路径。 *///读取文件。在web项目下不要这样读取。因为.表示在tomcat/bin目录下/*File file = new File("./src/db.properties");FileInputStream in = new FileInputStream(file);*//** * 使用web应用下加载资源文件的方法 *//** * 1. getRealPath读取,返回资源文件的绝对路径 *//*String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");System.out.println(path);File file = new File(path);FileInputStream in = new FileInputStream(file);*//** * 2. getResourceAsStream() 得到资源文件,返回的是输入流 */InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");Properties prop = new Properties();//读取资源文件prop.load(in);String user = prop.getProperty("user");String password = prop.getProperty("password");System.out.println("user="+user);System.out.println("password="+password);}}

3 Cooke技术

  

           3.1 特点

           Cookie技术:会话数据保存在浏览器客户端。

           3.2 Cookie技术核心

           Cookie类:用于存储会话数据

 

              1)构造Cookie对象

                  Cookie(java.lang.String name,java.lang.String value)

              2)设置cookie

                  void setPath(java.lang.Stringuri)   :设置cookie的有效访问路径

                  void setMaxAge(int expiry) : 设置cookie的有效时间

                  void setValue(java.lang.StringnewValue) :设置cookie的值

              3)发送cookie到浏览器端保存

                  void response.addCookie(Cookiecookie)  : 发送cookie

              4)服务器接收cookie

                  Cookie[]request.getCookies()  : 接收cookie

           3.3 Cookie原理

              1)服务器创建cookie对象,把会话数据存储到cookie对象中。

                     newCookie("name","value");

               2) 服务器发送cookie信息到浏览器

                     response.addCookie(cookie);

                  举例: set-cookie:name=eric  (隐藏发送了一个set-cookie名称的响应头)

              3)浏览器得到服务器发送的cookie,然后保存在浏览器端。

              4)浏览器在下次访问服务器时,会带着cookie信息

                      举例: cookie: name=eric  (隐藏带着一个叫cookie名称的请求头)

              5)服务器接收到浏览器带来的cookie信息

                     request.getCookies();

           3.4 Cookie的细节

           1)void setPath(java.lang.String uri)   :设置cookie的有效访问路径。有效路径指的是cookie的有效路径保存在哪里,那么浏览器在有效路径下访问服务器时就会带着cookie信息,否则不带cookie信息。

           2)void setMaxAge(int expiry) : 设置cookie的有效时间。

                  正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。

                  负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了!!

                  零:表示删除同名的cookie数据

           3)Cookie数据类型只能保存非中文字符串类型的。可以保存多个cookie,但是浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。

           3.5 案例- 显示用户上次访问的时间

    

package com.xp.cookie;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 第一个cookie的程序 */public class CookieDemo1 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//1.创建Cookie对象Cookie cookie1 = new Cookie("name","eric");//Cookie cookie2 = new Cookie("email","jacky@qq.com");//Cookie cookie1 = new Cookie("email","eric@qq.com");/** * 1)设置cookie的有效路径。默认情况:有效路径在当前web应用下。 /day11 *///cookie1.setPath("/day11");//cookie2.setPath("/day12");/** * 2)设置cookie的有效时间 * 正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了!!零:表示删除同名的cookie数据 *///cookie1.setMaxAge(20); //20秒,从最后不调用cookie开始计算cookie1.setMaxAge(-1); //cookie保存在浏览器内存(会话cookie)//cookie1.setMaxAge(0);//2.把cookie数据发送到浏览器(通过响应头发送: set-cookie名称)//response.setHeader("set-cookie", cookie.getName()+"="+cookie.getValue()+",email=eric@qq.com");//推荐使用这种方法,避免手动发送cookie信息response.addCookie(cookie1);//response.addCookie(cookie2);//response.addCookie(cookie1);//3.接收浏览器发送的cookie信息/*String name = request.getHeader("cookie");System.out.println(name);*/Cookie[] cookies = request.getCookies();//注意:判断null,否则空指针if(cookies!=null){//遍历for(Cookie c:cookies){String name = c.getName();String value = c.getValue();System.out.println(name+"="+value);}}else{System.out.println("没有接收cookie数据");}}}删除cookieimport java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DeleteCookie extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/** * 需求: 删除cookie */Cookie cookie = new Cookie("name","xxxx");cookie.setMaxAge(0);//删除同名的cookieresponse.addCookie(cookie);System.out.println("删除成功");}}用户上次访问时间package com.xp.cookie;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class HistServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");//获取当前时间SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");String curTime = format.format(new Date());//取得cookieCookie[] cookies = request.getCookies();String lastTime = null;if(cookies!=null){for (Cookie cookie : cookies) {if(cookie.getName().equals("lastTime")){//有lastTime的cookie,已经是第n次访问lastTime = cookie.getValue();//上次访问的时间//第n次访问//1.把上次显示时间显示到浏览器response.getWriter().write("欢迎回来,你上次访问的时间为:"+lastTime+",当前时间为:"+curTime);//2.更新cookiecookie.setValue(curTime);cookie.setMaxAge(1*30*24*60*60);//3.把更新后的cookie发送到浏览器response.addCookie(cookie);break;}}}/** * 第一次访问(没有cookie 或 有cookie,但没有名为lastTime的cookie) */if(cookies==null || lastTime==null){//1.显示当前时间到浏览器response.getWriter().write("你是首次访问本网站,当前时间为:"+curTime);//2.创建Cookie对象Cookie cookie = new Cookie("lastTime",curTime);cookie.setMaxAge(1*30*24*60*60);//保存一个月//3.把cookie发送到浏览器保存response.addCookie(cookie);}}}

案例-查看用户浏览器过的商品package com.xp.entity;public class Product {private String id;private String proName;private String proType;private double price;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getProName() {return proName;}public void setProName(String proName) {this.proName = proName;}public String getProType() {return proType;}public void setProType(String proType) {this.proType = proType;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public Product(String id, String proName, String proType, double price) {super();this.id = id;this.proName = proName;this.proType = proType;this.price = price;}public Product() {super();// TODO Auto-generated constructor stub}@Overridepublic String toString() {return "Product [id=" + id + ", price=" + price + ", proName="+ proName + ", proType=" + proType + "]";}}package com.xp.dao;import java.util.ArrayList;import java.util.List;import com.xp.entity.Product;/** * 该类中存放对Prodcut对象的CRUD方法 */public class ProductDao {//模拟"数据库",存放所有商品数据private static List<Product> data = new ArrayList<Product>();/** * 初始化商品数据 */static{//只执行一次for(int i=1;i<=10;i++){data.add(new Product(""+i,"笔记本"+i,"LN00"+i,34.0+i));}}/** * 提供查询所有商品的方法 */public List<Product> findAll(){return data;}/** * 提供根据编号查询商品的方法 */public Product findById(String id){for(Product p:data){if(p.getId().equals(id)){return p;}}return null;}}package com.xp.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xp.dao.ProductDao;import com.xp.entity.Product;/** * 查询所有商品的servlet * @author APPle * */public class ListServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");//1.读取数据库,查询商品列表ProductDao dao = new ProductDao();List<Product> list = dao.findAll();//2.把商品显示到浏览器PrintWriter writer = response.getWriter();String html = "";html += "<html>";html += "<head>";html += "<title>显示商品列表</title>";html += "</head>";html += "<body>";html += "<table border='1' align='center' width='600px'>";html += "<tr>";html += "<th>编号</th><th>商品名称</th><th>商品型号</th><th>商品价格</th>";html += "</tr>";//遍历商品if(list!=null){for(Product p:list){html += "<tr>";// /day11_hist/DetailServlet?id=1 访问DetailSErvlet的servlet程序,同时传递 名为id,值为1 的参数html += "<td>"+p.getId()+"</td><td><a href='"+request.getContextPath()+"/DetailServlet?id="+p.getId()+"'>"+p.getProName()+"</a></td><td>"+p.getProType()+"</td><td>"+p.getPrice()+"</td>";html += "<tr>";}}html += "</table>";/** * 显示浏览过的商品 */html += "最近浏览过的商品:<br/>";//取出prodHist的cookieCookie[] cookies = request.getCookies();if(cookies!=null){for (Cookie cookie : cookies) {if(cookie.getName().equals("prodHist")){String prodHist = cookie.getValue(); // 3,2,1String[] ids = prodHist.split(",");//遍历浏览过的商品idfor (String id : ids) {//查询数据库,查询对应的商品Product p = dao.findById(id);//显示到浏览器html += ""+p.getId()+" "+p.getProName()+" "+p.getPrice()+"<br/>";}}}}html += "</body>";html += "</html>";writer.write(html);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}package gz.itcast.servlet;import gz.itcast.dao.ProductDao;import gz.itcast.entity.Product;import java.io.IOException;import java.io.PrintWriter;import java.util.Arrays;import java.util.Collection;import java.util.LinkedList;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 显示商品详细 * @author APPle * */public class DetailServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");//1.获取编号String id = request.getParameter("id");//2.到数据库中查询对应编号的商品ProductDao dao = new ProductDao();Product product = dao.findById(id);//3.显示到浏览器PrintWriter writer = response.getWriter();String html = "";html += "<html>";html += "<head>";html += "<title>显示商品详细</title>";html += "</head>";html += "<body>";html += "<table border='1' align='center' width='300px'>";if(product!=null){html += "<tr><th>编号:</th><td>"+product.getId()+"</td></tr>";html += "<tr><th>商品名称:</th><td>"+product.getProName()+"</td></tr>";html += "<tr><th>商品型号:</th><td>"+product.getProType()+"</td></tr>";html += "<tr><th>商品价格:</th><td>"+product.getPrice()+"</td></tr>";}html += "</table>";html += "<center><a href='"+request.getContextPath()+"/ListServlet'>[返回列表]</a></center>";html += "</body>";html += "</html>";writer.write(html);/** * 创建cookie,并发送 *///1.创建cookieCookie cookie = new Cookie("prodHist",createValue(request,id));cookie.setMaxAge(1*30*24*60*60);//一个月//2.发送cookieresponse.addCookie(cookie);}private String createValue(HttpServletRequest request,String id) {Cookie[] cookies = request.getCookies();String prodHist = null;if(cookies!=null){for (Cookie cookie : cookies) {if(cookie.getName().equals("prodHist")){prodHist = cookie.getValue();break;}}}// null或没有prodHistif(cookies==null || prodHist==null){//直接返回传入的idreturn id;}// 3,21          2//String -> String[] ->  Collection :为了方便判断重复idString[] ids = prodHist.split(",");Collection colls = Arrays.asList(ids); //<3,21>// LinkedList 方便地操作(增删改元素)集合// Collection -> LinkedListLinkedList list = new LinkedList(colls);//不超过3个if(list.size()<3){//id重复if(list.contains(id)){//去除重复id,把传入的id放最前面list.remove(id);list.addFirst(id);}else{//直接把传入的id放最前面list.addFirst(id);}}else{//等于3个//id重复if(list.contains(id)){//去除重复id,把传入的id放最前面list.remove(id);list.addFirst(id);}else{//去最后的id,把传入的id放最前面list.removeLast();list.addFirst(id);}}// LinedList -> String StringBuffer sb = new StringBuffer();for (Object object : list) {sb.append(object+",");}//去掉最后的逗号String result = sb.toString();result = result.substring(0, result.length()-1);return result;}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

4 Session技术
4.1 引入
Cookie的局限:
1)Cookie只能存字符串类型。不能保存对象
2)只能存非中文。
3)1个Cookie的容量不超过4KB。
如果要保存非字符串,超过4kb内容,只能使用session技术!!!
Session特点:
会话数据保存在服务器端。(内存中)
4.2 Session技术核心
HttpSession类:用于保存会话数据
1)创建或得到session对象
HttpSession getSession()  
HttpSession getSession(boolean create)  
2)设置session对象
void setMaxInactiveInterval(int interval)  : 设置session的有效时间
void invalidate()     : 销毁session对象
java.lang.String getId()  : 得到session编号
3)保存会话数据到session对象
void setAttribute(java.lang.String name, java.lang.Object value)  : 保存数据
java.lang.Object getAttribute(java.lang.String name)  : 获取数据
void removeAttribute(java.lang.String name) : 清除数据
4.3 Session原理
问题: 服务器能够识别不同的浏览者!!!
现象:
  前提: 在哪个session域对象保存数据,就必须从哪个域对象取出!!!!
浏览器1:(给s1分配一个唯一的标记:s001,把s001发送给浏览器)
1)创建session对象,保存会话数据
HttpSession session = request.getSession();   --保存会话数据 s1
浏览器1 的新窗口(带着s001的标记到服务器查询,s001->s1,返回s1)
2)得到session对象的会话数据
   HttpSession session = request.getSession();   --可以取出  s1
新的浏览器1:(没有带s001,不能返回s1)
3)得到session对象的会话数据
   HttpSession session = request.getSession();   --不可以取出  s2


浏览器2:(没有带s001,不能返回s1)
4)得到session对象的会话数据
   HttpSession session = request.getSession();  --不可以取出  s3

代码解读:HttpSession session = request.getSession();

1)第一次访问创建session对象,给session对象分配一个唯一的ID,叫JSESSIONID
new HttpSession();
2)把JSESSIONID作为Cookie的值发送给浏览器保存
Cookie cookie = new Cookie("JSESSIONID", sessionID);
response.addCookie(cookie);
3)第二次访问的时候,浏览器带着JSESSIONID的cookie访问服务器
4)服务器得到JSESSIONID,在服务器的内存中搜索是否存放对应编号的session对象。
if(找到){
return map.get(sessionID);
}
Map<String,HttpSession>]
<"s001", s1>
<"s001,"s2>
5)如果找到对应编号的session对象,直接返回该对象
6)如果找不到对应编号的session对象,创建新的session对象,继续走1的流程

结论:通过JSESSION的cookie值在服务器找session对象!!!!!
4.4 Sesson细节
1)java.lang.String getId()  : 得到session编号
2)两个getSession方法:
getSession(true) / getSession()  : 创建或得到session对象。没有匹配的session编号,自动创建新的session对象。
getSession(false):              得到session对象。没有匹配的session编号,返回null
3)void setMaxInactiveInterval(int interval)  : 设置session的有效时间
session对象销毁时间:
3.1 默认情况30分服务器自动回收
3.2 修改session回收时间
3.3 全局修改session有效时间

<!-- 修改session全局有效时间:分钟 -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>


3.4.手动销毁session对象
void invalidate()     : 销毁session对象
4)如何避免浏览器的JSESSIONID的cookie随着浏览器关闭而丢失的问题
/**
* 手动发送一个硬盘保存的cookie给浏览器
*/
Cookie c = new Cookie("JSESSIONID",session.getId());
c.setMaxAge(60*60);
response.addCookie(c);


总结:
1)会话管理: 浏览器和服务器会话过程中的产生的会话数据的管理。
2)Cookie技术:
new Cookie("name","value")
response.addCookie(coookie)
request.getCookies()
3)Session技术
request.getSession();

setAttrbute("name","会话数据");
getAttribute("会话数据")

package com.xp.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * 保存会话数据到session域对象*/public class SessionDemo1 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//1.创建session对象HttpSession session = request.getSession();/** * 得到session编号 */System.out.println("id="+session.getId());/** * 修改session的有效时间 *///session.setMaxInactiveInterval(20);/** * 手动发送一个硬盘保存的cookie给浏览器 */Cookie c = new Cookie("JSESSIONID",session.getId());c.setMaxAge(60*60);response.addCookie(c);//2.保存会话数据session.setAttribute("name", "rose");}}package com.xp.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * 从session域对象中取出会话数据 * @author APPle * */public class SessionDemo2 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//1.得到session对象HttpSession session = request.getSession(false);if(session==null){System.out.println("没有找到对应的sessino对象");return;}/** * 得到session编号 */System.out.println("id="+session.getId());//2.取出数据String name = (String)session.getAttribute("name");System.out.println("name="+name);}}package com.xp.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * 销毁session对象*/public class DeleteSession extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {HttpSession session = request.getSession(false);if(session!=null){session.invalidate();//手动销毁}System.out.println("销毁成功");}}






0 0
原创粉丝点击