1.ServletConfig

ServletConfig:代表当前Servlet在web.xml中的配置信息

  • String getServletName()  -- 获取当前Servlet在web.xml中配置的名字
  • String getInitParameter(String name) -- 获取当前Servlet指定名称的初始化参数的值
  • Enumeration getInitParameterNames()  -- 获取当前Servlet所有初始化参数的名字组成的枚举
  • ServletContext getServletContext()  -- 获取代表当前web应用的ServletContext对象

在Servlet的配置文件中,可以使用一个或多个<init-param>标签为servlet配置一些初始化参数

当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中

配置Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Servlet_ServletConfig</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>AchieveParam</servlet-name>
<servlet-class>com.servlets.AchieveParamServlet</servlet-class> <init-param>
<param-name>userName</param-name>
<param-value>jtx</param-value>
</init-param>
<init-param>
<param-name>userPwd</param-name>
<param-value>123456</param-value>
</init-param> <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AchieveParam</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

Servlet处理类

package com.servlets;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; /**
* 可以实现Servlet接口
*
* @author yyx 2019年3月13日
*/
public class AchieveParamServlet extends HttpServlet {
private static final long serialVersionUID = 1L; @Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置输出内容的编码方式
response.setCharacterEncoding("UTF-8"); // 获得Session
HttpSession httpSession = request.getSession(); // 获得ServletConfig对象
ServletConfig servletConfig = this.getServletConfig();
String userName = servletConfig.getInitParameter("userName");
String userPwd = servletConfig.getInitParameter("userPwd");
httpSession.setAttribute("userName", userName);
httpSession.setAttribute("userPwd", userPwd);
/*
* getServletName()获取当前Servlet在web.xml中配置的名字
* getServletContext()获取代表当前web应用的ServletContext对象
* getInitParameterNames()获取当前Servlet所有初始化参数的名字组成的枚举
*/
System.out.println(servletConfig.getServletName());
ServletContext sContext = servletConfig.getServletContext(); Enumeration<String> enumeration = servletConfig.getInitParameterNames();
while (enumeration.hasMoreElements()) {
String name= enumeration.nextElement();
String value = servletConfig.getInitParameter(name);
System.out.println(value);
} // 转发
request.getRequestDispatcher("/success.jsp").forward(request, response);
} @Override
public void destroy() {
super.destroy();
System.out.println("Servlet销毁");
} @Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("Servlet初始化");
} }

JSP页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/achieveparamservlet.do">获取参数</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>${ userName}</h2>
<h2>${ userPwd}</h2>
</body>
</html>

2.ServletContext

ServletContext官方叫servlet上下文

     WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用

  • 是一个域对象
  • 可以读取全局配置参数
  • 可以搜索当前工程目录下面的资源文件
  •  可以获取当前工程名字

配置Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Servlet_ServletConfig</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>company</param-name>
<param-value>Alibaba</param-value>
</context-param>
<servlet>
<servlet-name>AchieveParam</servlet-name>
<servlet-class>com.servlets.AchieveParamServlet</servlet-class> <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AchieveParam</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

Servlet处理类

package com.servlets;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties; import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; /**
* 可以实现Servlet接口
*
* @author yyx 2019年3月13日
*/
public class AchieveParamServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private int count; @Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置输出内容的编码方式
response.setCharacterEncoding("UTF-8"); // 获得Session
HttpSession httpSession = request.getSession(); // 获得ServletContext对象,读取全局参数
ServletContext servletContext = this.getServletContext();
String company = servletContext.getInitParameter("company");
httpSession.setAttribute("company", company); Enumeration<String> names = servletContext.getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = servletContext.getInitParameter(name);
System.out.println(value);
} // web应用范围内共享数据,每调用一次方法都会加1
servletContext.setAttribute("count", count++); // 读取配置文件
InputStream is = servletContext.getResourceAsStream("/WEB-INF/classes/jdbc.properties");
Properties properties = new Properties();
properties.load(is);
System.out.println(properties.getProperty("driverClass"));
System.out.println(properties.getProperty("url"));
is.close(); // 获取工程名称
System.out.println(servletContext.getContextPath());
// 转发
request.getRequestDispatcher("/success.jsp").forward(request, response);
} @Override
public void destroy() {
super.destroy();
System.out.println("Servlet销毁");
} @Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("Servlet初始化");
} }

JSP页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/achieveparamservlet.do">获取参数</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>${ company}</h2>
<h2>${ count}</h2>
</body>
</html>

JavaWeb-----ServletConfig对象和servletContext对象的更多相关文章

  1. Java Servlet(三):Servlet中ServletConfig对象和ServletContext对象

    本文将记录ServletConfig/ServletContext中提供了哪些方法,及方法的用法. ServletConfig是一个抽象接口,它是由Servlet容器使用,在一个servlet对象初始 ...

  2. 小谈-—ServletConfig对象和servletContext对象

    一.servletContext概述 servletContext对象是Servlet三大域对象之一,每个Web应用程序都拥有一个ServletContext对象,该对象是Web应用程序的全局对象或者 ...

  3. ServletConfig对象和ServletContext对象有什么区别?

    一个Servlet对应有一个ServletConfig对象,可以用来读取初始化参数. 一个webapp对应一个ServletContext对象. ServletContext对象获取初始化定义的参数. ...

  4. ServletConfig对象和ServletContext对象

    (1)ServletConfig:用来保存一个Servlet的配置信息的(比如 : name, class, url ... ) 这些配置信息没什么大用处,我们还可以在ServletConfig中保存 ...

  5. Servlet接口的实现类,路径配置映射,ServletConfig对象,ServletContext对象及web工程中文件的读取

    一,Servlet接口实现类:sun公司为Servlet接口定义了两个默认的实现类,分别为:GenericServlet和HttpServlet. HttpServlet:指能够处理HTTP请求的se ...

  6. IT兄弟连 JavaWeb教程 ServletContext对象

    ServletContext是Servlet与Servlet容器之间直接通信的接口.Servlet容器在启动一个Web应用时,会为它创建一个ServletContext对象.每个Web应用都有唯一的S ...

  7. 重温Servlet学习笔记--servletContext对象

    一个项目中只有一个ServletContext对象,我们可以在多个servlet中获取这个唯一的对象,使用它可以给多个servlet传递数据,我们通常成servletContext为上下文对象.这个对 ...

  8. Java第三阶段学习(十一、Servlet基础、servlet中的方法、servlet的配置、ServletContext对象)

    一.Servlet简介  1.什么是servlet: sun公司提供的一套规范(接口),用来处理客户端请求.响应给浏览器的动态资源.但servlet的实质就是java代码,通过java的API动态的向 ...

  9. [Servlet]研究ServletContext对象

    作者信息 作者姓名:金云龙 个人站点:http://www.longestory.com 个人公众帐号:搜索"longestory"或"龙哥有话说" Servl ...

随机推荐

  1. 恒生UFX接口引用计数心得

    本文介绍在基于恒生T2SDK基础上开发对接UFX柜台时,有关引用计数的一些心得体会. 下面以配置接口和连接接口为例子来介绍,下面是文档介绍: 创建配置接口说明: 3.1.2 创建配置接口(NewCon ...

  2. 21 go并发编程-下

    如何等待一组goroutine结束 1. 使用不带缓冲区的channel实现. 原理: 每个goroutine都往一个channel里写入一个值,然后我们去遍历这个管道的数值,由于不带缓冲区,那么必须 ...

  3. application.properties配置文件

    SpringBoot可以识别两种格式的配置文件,分别是yml文件与properties文件,可以将application.properties文件换成application.yml applicati ...

  4. java.lang.ClassCastException:weblogic.xml.jaxp.RegistryDocumentBuilderFactory cannot be cast to javax.xml.parsers.DocumentBuilderFactory

    java.lang.ClassCastException:weblogic.xml.jaxp.RegistryDocumentBuilderFactory cannot be cast to java ...

  5. Oracle密码过期问题 ORA-28001:the password has expired

    如果已经过期了,首先需要修改密码,然后设置密码为无限期.修改以sys用户登陆. 修改密码:alter user username identified by password  密码可以和之前的密码相 ...

  6. 程序中的@Override是什么意思?

    @Override是Java5的元数据,自动加上去的一个标志,告诉你说下面这个方法是从父类/接口 继承过来的,需要你重写一次,这样就可以方便你阅读,也不怕会忘记 @Override是伪代码,表示重写( ...

  7. mui---获取设备的网络状态

    在用mui做音乐或视频播放器的时候,往往会考虑当前音乐+视频的播放环境.例如是4G ,WIFI,无网络,给出特定的提示: 具体做法:根据 getCurrentType来进行获取当前网络的类型: plu ...

  8. python set和get实现

    import math class Square: # 正方形 def __init__(self, l): self.length = l # 边长 def __setattr__(self, ke ...

  9. 解决ssh出现"Write failed: Broken pipe"问题

    用 ssh 命令连接服务器之后,如果一段时间不操作,再次进入 Terminal 时会有一段时间没有响应,然后就出现错误提示: Write failed: Broken pipe 只能重新用 ssh 命 ...

  10. route 配置默认网关

    影响Linux系统网络中网关配置信息的3种方式 1.生效文件cat /etc/sysconfig/network-scripts/ifcfg-eth0 GATEWAY=10.0.0.254 <- ...