标签:
package secondWeb;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
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 second extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
/*application与session
* 1、两者都可以用一个名字来绑定一个对象,从而在与范围内进行访问
* 2、生命周期不同。session仅存在于声明的时间内;application在web应用程序运行过程中都存在*/
ServletContext con=this.getServletConfig().getServletContext();//获取应用上下文
String context=con.getInitParameter("context");//获取名叫“context”的值
out.print("通过application保存的名叫context的值为:"+context+"<br/>");
Cookie[] cookies = req.getCookies();//获取浏览器存储的全部cookie
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("name")) {//找到叫名字叫"name"的cookie
out.print("通过cookie保存的name值是:" + cookie.getValue()+"<br/>");
}
}
}
HttpSession se = req.getSession(false);//根据保存在cookie中的sessionid获取存储在服务器的session
if (se == null) {
out.print("没有保存的session");
}else{
out.print("通过session保存的pwd值是:" + se.getAttribute("pwd"));}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
标签:
原文地址:http://www.cnblogs.com/quanby/p/5612383.html