Tomcat中获取资源文件:

ServletContext().getRealPath(/WEB-INF/classes/db.properties);//获取资源文件的在服务器中的绝对路径

 ServletContext()getResourceAsStream() 得到资源文件,返回的是输入流

ServletContext().getRealPath

会话管理

  1.定义:管理浏览器和服务器间会话期间产生的会话数据

  2.域对象:实现资源之间数据的共享

  3.会话数据

    a) Cookie:会话数据保存在浏览器客户端

    1. 使用流程:

        1.Cookie对象在服务端被创建new Cookie(name,value,)->

        2.发送到客户端 respond.addCookie(cookie)(这里隐式发了一个set-Cookie的响应头set-Cookie:name=value)->

        3.浏览器得到这个Cookie会保存起来下次访问服务器时会带着Cookie信息(隐式带着一个Cookie:name=value的请求头)->

        4.服务器获得浏览器发来的Cookie对象request.getCookies()

    1.  主要方法

        构造:Cookie(String ,value);

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

            setValue(String newValue);//设置新的Cookie

            setPath(String path);//设置有效的访问路径

        发生:addCookie(cookie);

        服务端接受:request.getCookies();

    1. 注意:

        Cookie只能保存非中文字符串类型,可以保存多个多个Cookie,一个浏览器可以保存300Cookie,每个站点只能存20个,每个Cookie大小限制4kb;

        setMaxAge(int expiry):正数:保存在浏览器客户端硬盘时间;

         负数:保存在浏览器内存中,关闭浏览器就没有了

        零:删除同名的Cookie数据

    1.  例子:保存用户上次访问的时间
/**

 * 案例-用户上次访问时间

 * @author APPle

 *

 */

public class HistServlet 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");

 

//获取当前时间

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

String curTime = format.format(new Date());

 

 

//取得cookie

Cookie[] 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.更新cookie

cookie.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);

}

}

 

}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-23
  • 2023-01-30
  • 2021-04-05
猜你喜欢
  • 2021-10-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案