httpservlet----two

Posted 永远前进在路上

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpservlet----two相关的知识,希望对你有一定的参考价值。

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);
}

}

以上是关于httpservlet----two的主要内容,如果未能解决你的问题,请参考以下文章