zoukankan      html  css  js  c++  java
  • JavaWeb-----ServletConfig对象和servletContext对象

       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>
  • 相关阅读:
    tomcat bug之部署应用的时候经常会发上startup failed due to previous errors
    maven编译项目理解
    MyReport报表引擎2.6.5.0新功能
    PHP入门-摘要表格处理问题
    EnumMap源代码阅读器
    MySQL几种方法的数据库备份
    工作日志2014-08-19
    Linux通过网卡驱动程序和版本号的信息
    JS于,子类调用父类的函数
    hdu 5007 水 弦
  • 原文地址:https://www.cnblogs.com/fengfuwanliu/p/10518467.html
Copyright © 2011-2022 走看看