Servlet (一) 学习笔记

1.setContentType : 设置响应头类型,字符集

public class TwoServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter(); // 获取响应对象 (返回给浏览器的对象)
        out.print("Hellow,World"); // 给浏览器返回 "HelloWorld" 字符串
    }
}

2. ServletConfig 接口的4个方法:

getInitParameter(String name):获取Servlet配置的初始化参数值
参数:参数是要获取的初始化参数的名字。
返回值:返回指定名称的初始化参数值,如果不存在则返回null。
getInitParameterNames():获取所有初始化参数的名字
返回值:返回一个Enumeration<String>对象,包含所有的初始化参数名。如果没有初始化参数,则返回一个空的枚举。
getServletContext():获取与当前Servlet关联的ServletContext对象
ServletContext 相当于 整个web.xml文件,Tomcat 相当于一个容器.每个项目都是一个ServletContext
返回值:返回一个ServletContext对象,提供了对Servlet上下文环境的访问,包括可以获取Web应用程序范围内的信息和资源。
getServletName():获取Servlet的名称
返回值:返回一个字符串,表示Servlet的名称。这个名称是在web.xml中定义的,或者是容器分配给Servlet的默认名称(当没有显式指定时)。

获取servlet 的配置信息

public class MyServlet extends HttpServlet {
    public void init() throws ServletException {
        // 获取单个初始化参数
        String paramValue = getInitParameter("myParam");
        // 获取所有初始化参数的名字
        Enumeration<String> paramNames = getInitParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            System.out.println("Init parameter: " + paramName);
        }
        // 获取ServletContext对象
        ServletContext context = getServletContext();
        String contextParam = context.getInitParameter("contextParam");
        // 获取Servlet名称
        String servletName = getServletName();
        System.out.println("Servlet Name: " + servletName);
    }
}
ServletConfig servletConfig = this.getServletConfig(); 
// 使用this调用 getServletConfig的前提是 当前类 继承了 GenericServlet类 或 HttpServlet 类
servletConfig.getServletName(); // 获取初始化参数的name

3. ServletContext ( )常用方法

1) getInitParameter ()、getInitParameterNames ()

ServletContext() 的返回结果是对象,这个对象也有 getInitParameter 和 getInitParameterNames 方法
区别 :
ServletConfig 的初始化参数是针对单个Servlet的,配置在 <servlet>标签内。
ServletContext 的上下文参数是针对整个Web应用程序的,配置在<context-param>标签内。

public class MyServlet extends HttpServlet {
    private ServletConfig servletConfig;
    private ServletContext servletContext;
    public void init(ServletConfig config) throws ServletException {
        this.servletConfig = config;
        this.servletContext = config.getServletContext();
        // 获取ServletConfig中的初始化参数
        String servletParam = servletConfig.getInitParameter("myParam");
        Enumeration<String> servletParamNames = servletConfig.getInitParameterNames();
        // 获取ServletContext中的上下文参数
        String contextParam = servletContext.getInitParameter("appParam");
        Enumeration<String> contextParamNames = servletContext.getInitParameterNames();
        System.out.println("Servlet Param: " + servletParam);
        System.out.println("Context Param: " + contextParam);
        while (servletParamNames.hasMoreElements()) {
            String paramName = servletParamNames.nextElement();
            System.out.println("Servlet Init Parameter: " + paramName);
        }
        while (contextParamNames.hasMoreElements()) {
            String paramName = contextParamNames.nextElement();
            System.out.println("Context Init Parameter: " + paramName);
        }
    }
}

对应的XML,一般在 context-param

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!-- Servlet 配置 -->
    <servlet>
        <servlet-name>myServlet</servlet-name>
        <servlet-class>com.example.MyServlet</servlet-class>
        <!-- Servlet 初始化参数 -->
        <init-param>
            <param-name>myParam</param-name>
            <param-value>value1</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>myServlet</servlet-name>
        <url-pattern>/myServlet</url-pattern>
    </servlet-mapping>
    <!-- ServletContext 上下文参数 -->
    <!-- 配置公共的信息,例如 项目的分页大小 -->
    <context-param>
        <param-name>pageSize</param-name>
        <param-value>10</param-value>
    </context-param>
    <context-param>
        <param-name>pageIndex</param-name>
        <param-value>1</param-value>
    </context-param>
</web-app>
2) getContextPath() : 获取Web 应用程序的根路径

示例
假设你的 Web 应用程序部署在 http://example.com/myapp,那么 getContextPath() 将返回 /myapp

3) getRealPath() : 它用于将虚拟路径(相对于 Web 应用程序的根目录)转换为实际的服务器文件系统路径。这个方法在需要访问 Web 应用程序中的静态资源(如文件、图片、配置文件等)时非常有用

在某些部署环境中(例如某些应用服务器或云平台),文件系统路径可能不可用或受限。因此,在使用 getRealPath() 之前,最好检查返回值是否为 null。
示例

image.png

public class ExampleServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        
        // 获取 config.properties 文件的实际路径
        String configPath = context.getRealPath("/WEB-INF/config.properties");
        File configFile = new File(configPath);
        
        // 获取 logo.png 文件的实际路径
        String imagePath = context.getRealPath("/images/logo.png");
        File imageFile = new File(imagePath);
        
        response.setContentType("text/html");
        response.getWriter().println("<html><body>");
        response.getWriter().println("<h1>Config File Path: " + configPath + "</h1>");
        response.getWriter().println("<h1>Image File Path: " + imagePath + "</h1>");
        response.getWriter().println("</body></html>");
    }
}

4) log() : 记录日志

会记录到 Tomcat 的logs 目录下

5) setAttribute() getAttribute() : 从ServletContext 设置/ 获取属性

使用场景: 需要在多个 Servlet 之间共享的数据

//A 程序 设置一个 值  B 程序获取这个值
public class AServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
         // 设置一个属性
        request.setAttribute("name", "张三");
    }
}

public class BServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取属性
        String requestAttribute = (String) request.getAttribute("name");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355

推荐阅读更多精彩内容