1.路径问题:

注意 .代表执行程序的文件夹路径,在tomcat中也就是bin目录,所以要用this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");得到绝对路径;

代码练习:

package com.http.path;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class PathDemo extends HttpServlet { public PathDemo() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8"); //给服务器使用的: / 表示在当前web应用的根目录(webRoot下)
//request.getRequestDispatcher("/target.html").forward(request, response); //给浏览器使用的: / 表示在webapps的根目录下
//response.sendRedirect("/MyWeb/target.html"); String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
//this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
System.out.println(path);
Properties properties = new Properties();
properties.load(new FileInputStream(new File(path))); String user = properties.getProperty("user");
String passwd = properties.getProperty("passwd");
System.out.println("user = " + user + "\npasswd = " + passwd);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} public void init() throws ServletException {
// Put your code here
} }

2.Cooke技术

2.1 特点

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

2.2 Cookie技术核心

Cookie类:用于存储会话数据

1)构造Cookie对象

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

2)设置cookie

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

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

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

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

void response.addCookie(Cookie cookie)  : 发送cookie

4)服务器接收cookie

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

2.3 Cookie原理

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

new Cookie("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();

2.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。

在下面查了下,cookie也可以存中文字符串,可以用URLEncoder类中的encode方法编码,然后用URLDecoder.decode方法解码

cookie的简单练习:

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter; 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 CookieDemo1 extends HttpServlet { /**
* Constructor of the object.
*/
public CookieDemo1() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { Cookie cookie = new Cookie("name", "handsomecui");
Cookie cookie2 = new Cookie("email", "handsomecui@qq.com");
cookie2.setPath("/Test");
//cookie.setMaxAge(10);//不会受到浏览器关闭的影响
cookie.setMaxAge(-1);//cookie保存在浏览器内存,关闭移除
//cookie.setMaxAge(0);//删除同名cookie
response.addCookie(cookie);
response.addCookie(cookie2);
System.out.println(request.getHeader("cookie"));
Cookie[] cookies = request.getCookies();
if(cookies == null){
System.out.println("没有cookie");
}
else{
for(Cookie acookie : cookies){
System.out.println(acookie.getName() + "是" + acookie.getValue());
}
} } /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

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

代码:

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;
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 ShowTime extends HttpServlet { /**
* Constructor of the object.
*/
private int cnt = 0;
public ShowTime() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} private String Isexist(HttpServletRequest request){
Cookie[] cookies = request.getCookies();
if(cookies == null){
return null;
}
for(Cookie acookie:cookies){
if("lasttime".equals(acookie.getName())){
return acookie.getValue();
}
}
return null;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
cnt++;
response.setCharacterEncoding("gb2312");
request.setCharacterEncoding("gb2312"); response.getWriter().write("您好,这是您第" + cnt + "次访问本站\n");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String str = format.format(new Date());
Cookie cookie = new Cookie("lasttime", str);
response.addCookie(cookie);
String lasttime = Isexist(request);
if(lasttime != null){
response.getWriter().write("您上次访问的时间是:" + lasttime + "\n");
}else{ }
response.getWriter().write("当前时间是:" + str + "\n");
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

2.6 案例-查看用户浏览器过的商品

思路:ListServlet展示商品列表,Detailservlet展示商品的详细信息,最近浏览的商品,用一个hashset存储MySet类,取出前三个不重复的即可,cookie存放最近浏览的商品编号,用逗号隔开;

product类:

package com.common.product;

import java.util.ArrayList;

public class Product {
private static ArrayList<Product>arrayList;
private int id;
private String name;
private String type;
private double price;
static{
arrayList = new ArrayList<Product>();
for(int i = 0; i < 10; i++){
Product product = new Product(i + 1, "笔记本"+(i + 1), "LN00"+(i+1), 35+i);
arrayList.add(product);
}
}
public static ArrayList<Product> getArrayList() {
return arrayList;
}
@Override
public String toString() {
return "id=" + id + ", name=" + name + ", type=" + type
+ ", price=" + price ;
}
public Product(int id, String name, String type, double price) {
super();
this.id = id;
this.name = name;
this.type = type;
this.price = price;
}
public Product() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Product getValueById(int p) {
for(int i = 0; i < arrayList.size(); i++){
if(arrayList.get(i).getId() == p){
return arrayList.get(i);
}
}
return null;
} }

MySet类:由编号和商品名构成,主要是为了hashset的去重与排序;

package com.common.tool;

import java.util.HashSet;

public class MySet{
private int id;
private String name;
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
MySet myset = (MySet)o;
return myset.getName().equals(this.getName());
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MySet(int id, String name) {
super();
this.id = id;
this.name = name;
}
public MySet() {
super();
} }

ListServlet:

package com.http.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList; 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.common.product.Product; public class ListServlet extends HttpServlet { /**
* Constructor of the object.
*/
public ListServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Product product = new Product();
String html = "";
html+=("<html>");
html+=("<head>");
html+=("<meta charset='utf-8'/>"); html+=("<title>");
html+=("商品列表");
html+=("</title>");
html+=("</head>");
html+=("<body>");
html+=("<table align='center' border='1'>");
html+=("<tr>");
html+=("<th>");
html+=("编号");
html+=("</th>");
html+=("<th>");
html+=("商品名称");
html+=("</th>");
html+=("<th>");
html+=("商品型号");
html+=("</th>");
html+=("<th>");
html+=("商品价格");
html+=("</th>");
html+=("</tr>");
ArrayList<Product> list = new Product().getArrayList();
for(int i = 0; i < list.size(); i++){
html+=("<tr>");
html+=("<td>");
html+=("" + list.get(i).getId());
html+=("</td>");
html+=("<td>");
html+=("<a href = '"+ request.getContextPath() +"/DetailServlet"+"?id="+list.get(i).getId()+"'>" + list.get(i).getName() + "</a>");
html+=("</td>");
html+=("<td>");
html+=(list.get(i).getType());
html+=("</td>");
html+=("<td>");
html+=("" + list.get(i).getPrice());
html+=("</td>");
html+=("</tr>");
}
html+=("</table>");
html+=("最近浏览过的商品: " + "<br/>");
String recentview = null;
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if("RecentProduct".equals(cookie.getName())){
recentview = cookie.getValue();
break;
}
}
}
if(recentview != null){
recentview = URLDecoder.decode(recentview, "UTF-8");
String[] splits = recentview.split(",");
for(String p : splits){
html += (product.getValueById(Integer.parseInt(p)) + "<br/>");
}
}
html+=("</body>");
html+=("</html>");
response.getWriter().write(html);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

DetailServlet

package com.http.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Stack;
import java.net.URLEncoder; 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.common.product.Product;
import com.common.tool.MySet; @SuppressWarnings("unused")
public class DetailServlet extends HttpServlet { /**
* Constructor of the object.
*/
public DetailServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
int id = Integer.parseInt(request.getParameter("id"));
System.out.println(id);
Product product = new Product().getValueById(id);
String html = "";
html+=("<html>");
html+=("<head>");
html+=("<meta charset='utf-8'/>");
html+=("<title>");
html+=("商品信息");
html+=("</title>");
html+=("</head>");
html+=("<body>");
html+=("<table align='center' border='1'>"); html+=("<tr>");
html+=("<th>");
html+=("编号");
html+=("</th>");
html+=("<td>");
html+=(id);
html+=("</td>");
html+=("</tr>"); html+=("<tr>");
html+=("<th>");
html+=("商品名称");
html+=("</th>");
html+=("<td>");
html+=(product.getName());
html+=("</td>");
html+=("</tr>"); html+=("<tr>");
html+=("<th>");
html+=("商品型号");
html+=("</th>");
html+=("<td>");
html+=(product.getType());
html+=("</td>");
html+=("</tr>"); html+=("<tr>");
html+=("<th>");
html+=("商品价格");
html+=("</th>");
html+=("<td>");
html+=(product.getPrice());
html+=("</td>");
html+=("</tr>"); html+=("</body>");
html+=("</html>");
Cookie acookie = null;
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if("RecentProduct".equals(cookie.getName())){
acookie = cookie;
break;
}
}
}
System.out.println(product.getName());
if(acookie == null){
acookie = new Cookie("RecentProduct", product.getId()+"");
response.addCookie(acookie);
}else{
String[] splits = acookie.getValue().split(",");
HashSet<MySet> set = new HashSet<MySet>();
set.add(new MySet(0, product.getId()+""));
for(int i = 0, j = 0; i < splits.length;i++){
if((product.getId()+"").equals(splits[i]))
continue;
j++;
set.add(new MySet(j, splits[i]));
} String value = "";
Iterator<MySet> iterator = set.iterator();
for(int i = 0; iterator.hasNext()&& i < 3; i++){
MySet mySet = iterator.next();
value += (mySet.getName() + ",");
}
acookie = new Cookie("RecentProduct", value);
response.addCookie(acookie);
}
response.getWriter().write(html);
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

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)

1)得到session对象的会话数据

HttpSession session = request.getSession();   --可以取出  s1

新的浏览器1:(没有带s001,不能返回s1)

1)得到session对象的会话数据

HttpSession session = request.getSession();   --不可以取出  s2

浏览器2:(没有带s001,不能返回s1)

1)得到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);

代码SessionDemo1

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder; 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; public class SessionDemo1 extends HttpServlet { /**
* Constructor of the object.
*/
public SessionDemo1() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { HttpSession session = request.getSession();
System.out.println("id = "+session.getId());
session.setAttribute("name", "rose");
session.setMaxInactiveInterval(60*60);
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(60*60);
response.addCookie(cookie); } /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

SessionDemo2:

package com.http.cookie;

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 SessionDemo2 extends HttpServlet { /**
* Constructor of the object.
*/
public SessionDemo2() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { HttpSession session = request.getSession(false);
if(session != null){
System.out.println(session.getAttribute("name"));
}
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

DeleteSession

package com.http.cookie;

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 DeleteSession extends HttpServlet { /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { HttpSession session = request.getSession(false);
if(session != null){
session.invalidate();
System.out.println("销毁成功");
}
} }

路径问题以及cookie详解的更多相关文章

  1. cookie详解

    一.cookie详解 (1)设置cookie 每个cookie都是一个名/值对,可以把下面这样一个字符串赋值给document.cookie: document.cookie="userId ...

  2. 网络基础 cookie详解

    cookie详解 by:授客 QQ:1033553122 cookie干嘛用的? 参见文章http 会话(session)详解: 网络基础 http 会话(session)详解   cookie分类 ...

  3. cookie详解(含vue-cookie)

    今天看到一篇cookie的文章,写的特别详细,感谢 晚晴幽草轩 的分享,原文链接http://mp.weixin.qq.com/s/NXrH7R8y2Dqxs9Ekm0u33w 原文如下,记录到此供以 ...

  4. Session和Cookie详解(1)

    面试常问的有关session和cookie的问题: 1.session在分布式环境下怎么解决 2.集群下如何保证session踩中 3.cookie的大小 4.服务器怎么识别一个用户的 5.sessi ...

  5. Cookie 详解以及实现一个 cookie 操作库

    Cookie 详解以及实现一个 cookie 操作库 cookie 在前端有着大量的应用,但有时我们对它还是一知半解.下面来看看它的一些具体的用法 Set-Cookie 服务器通过设置响应头来设置客户 ...

  6. [转]Cookie详解

    从事 Web 开发已有近17个月:在学以致用的工作学习里,对于不怎么使用的部分,多少有些雾里探花的窘迫感-差不多是了解一二,然而又非真切的明晰:这就使得再用的时候,总要去再搜索一番:如此颇为难受,倒不 ...

  7. Cookie的使用、Cookie详解、HTTP cookies 详解、获取cookie的方法、客户端获取Cookie、深入解析cookie

    Cookie是指某些网站为了辨别用户身份.进行session跟踪而存储在用户本地终端上的数据(通常经过加密),比如说有些网站需要登录才能访问某个页面,在登录之前,你想抓取某个页面内容是不允许的.那么我 ...

  8. 转:Cookie详解

    没怎么坐过客户端相关的工作,所以写爬虫的时候,很多概念都很模糊,学习起来很困难.现在想攻坚一下,所以找了一下cookies相关的内容. HTTP cookies,通常又称作"cookies& ...

  9. session及cookie详解(七)

    前言 文章说明 在每整理一个技术点的时候,都要清楚,为什么去记录它.是为了工作上项目的需要?还是为了搭建技术基石,为学习更高深的技术做铺垫? 让每一篇文章都不是泛泛而谈,复制粘贴,都有它对自己技术提升 ...

随机推荐

  1. php捕获异常的处理

    try {            $result = *} catch (Exception $e) {            $result = $e; } 如果try里面报异常,$result = ...

  2. 迁移/home目录至新硬盘分区总结--无备份情况下

    搞了一天,终于成功迁移.由于一开始就没备份过程实在很曲折. 希望本篇对那些没有备份习惯的朋友们有所帮助. 准备工作: sudo vim /etc/fstab 在文件中加入: /dev/sdb8     ...

  3. java socket报文通信(一)socket的建立

    java socket报文通信(一) socket的建立  今天来和大家分享一下java中如何使用socket进行通信.先来啰嗦两句,看看Tcp/ip和udp: TCP是Transfer Contro ...

  4. C#数组反转

    static void Main(string[] arr) { string[] names = { "老杨1", "老李2", "老王3" ...

  5. libusb简介

    概述 libusb是一个C库,它提供了通用的访问USB设备. 它的目的是供开发人员使用方便的生产与USB通信硬件的应用程序. 可移植的: 使用一个跨平台API,它提供了访问USB设备在Linux上,O ...

  6. python3.5文档

    https://docs.python.org/3.5/tutorial/modules.html#packages

  7. angular启动过程分析

    启动过程 步骤一 用自执行函数在代码完成加载后立即执行 function(window, document, undefined) 在window上暴露一个唯一的全局对象angular,Line250 ...

  8. mysql 整形的长度问题

    tinyint  有符号的范围是-128至127: 无符号的范围是0到255,2的8 次方-1: 存储大小为 1 字节. smallint  有符号的范围是-32768至32767: 无符号的范围是0 ...

  9. php代码的一些高效写法

    用单引号代替双引号来包含字符串,这样做会更快一些.因为PHP会在双引号包围的字符串中搜寻变量,单引号则不会,注意:只有echo能这么做,它是一种可以把多个字符串当作参数的“函数”(译注:PHP手册中说 ...

  10. Js自动截取字符串长度,添加省略号“……”

    JavaScript字符串处理函数,根据定义的长度截取字符串,超出部分裁掉追加……,很多时候网页上显示的内容需要缩成“...”该方法用于处理字符串显示固定长度,超长部分用“...”代替: /**参数说 ...