1. Servlet 中如何获取 Session 对象?
使用HttpServletRequest对象的getSession方法获取session,通过getCookies获取Cookie。
2. Servlet 中过滤器有什么作用?
Servlet监听器对特定的事件进行监听,当产生这些事件的时候,会执行监听器的代码。可以对应用的加载、卸载,对session的初始化、销毁,对session中值变化等事件进行监听。
void doFilter(..) { // do stuff before servlet gets called// invoke the servlet, or any other filters mapped to the target servletchain.doFilter(..);// do stuff after the servlet finishes
}
3. ServletContext 接口包括哪些功能?分别用代码示例。
1、获取web应用的初始化参数
使用getInitParameterNames()和getInitParameter(String name)来获得web应用中的初始化参数。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");PrintWriter outPrintWriter = response.getWriter();ServletContext context = this.getServletContext(); //定义一个ServletContext对象Enumeration<String> enumeration = context.getInitParameterNames(); //用集合得方式存储配置文件中所有的namewhile(enumeration.hasMoreElements()){ //判断是否为空String nameString = enumeration.nextElement(); //跨过头部 提取第一个nameString passString = context.getInitParameter(nameString); //用getInitParameter(name)提取valueoutPrintWriter.print(nameString+" "+passString); //输出}
}
2、实现多个servlet的数据共享
setAttribute(String name,String value) 来设置共享的数据
getAttribute(String name) 来获得共享得数据值
removeAttribute(String name) 删除
getAttributeNames()
写数据:ServletSet类
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubServletContext context = this.getServletContext();context.setAttribute("CSDN:梦睡了", "123456");
}
读数据:ServletGet类
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubrequest.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();ServletContext context = this.getServletContext();String pasString = (String) context.getAttribute("CSDN:梦睡了"); //要强制类型转换getAttribute的返回值为objectout.print(pasString);
}
3、获取web应用下的资源文件(配置文件或图片)
InputS