Session的使用
1、取得session对象
req.getSession()方法
2、取得sessionId
getId()方法
3、设置session的最大空闲时间
setMaxInactiveInterval()
4、强制session失效
invalidate()
范例:
package com.zgy.servlet;
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;
public class TestSessionServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = req.getSession();
resp.getWriter().println(session.getId());
session.setMaxInactiveInterval(3);
}
}
八、ServletConfig
1、ServletConfig 一般用于处理该servlet在配置文件中的配置信息
范例:
package com.zgy.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServletConfig extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletConfig config = this.getServletConfig();
resp.getWriter().println(config.getInitParameter("a"));
resp.getWriter().println(config.getServletName());
Enumeration<?> e = config.getInitParameterNames();
while(e.hasMoreElements()){
resp.getWriter().println(e.nextElement());
}
resp.getWriter().println(config.getClass());
}
}
九、ServletContext对象
范例:
package com.zgy.servlet;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServletContext extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContext sc = this.getServletContext();
resp.getWriter().println(sc.getInitParameter("aa"));
//sc.setAttribute("c", new Date());
String str = sc.getRealPath("index.jsp");
resp.getWriter().println("realpath:"+str);
Set<String> set = sc.getResourcePaths("/WEB-INF");
for(String s : set){
resp.getWriter().println(s);
}
}
}