栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

P10 JavaWeb

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

P10 JavaWeb

在文件目录下创建一个新的servlet-02

创建一个node.md文件用来方便使用(方便配置每一次的web.xml)

web.xml
```xml



```

总目录层次:

 

三部曲走: 

提供资源的类(HelloServlet):

package com.Li.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //this.getInitParameterNames();多用this去‘.’函数。测试每个函数的效果。
        //System.out.println(this.getInitParameterNames());
        //得到java.util.Collections$3@1b1b002a
        //this.getServletConfig()   获取Servlet配置
        //this.getServletContext()   Servlet上下文****这是重点
        ServletContext context = this.getServletContext();

        String userName = "李";
        context.setAttribute("username", userName);//将一个数据保存在了ServletContest中,名字为username,存的内容是userName
    }
}

读取资源的类(GetServlet ): 

 

package com.Li.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GetServlet extends HttpServlet {
    //其实重写一个doGet就可以了。重写第二个是为了以后的一些内容不出问题。就相当于是模板。
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        //原型:context.getAttribute("username");==========下面是为了方便输出而进行了强制转换
        String username = (String) context.getAttribute("username");

        //在网页中显示防止中文乱码的配置
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        //在网页中显示
        resp.getWriter().print("名字"+username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

二者中间用 getServletContext当中介!

配置web.xml

 




   
      hello
      com.Li.servlet.HelloServlet
   
   
      hello
      /hello
   



   
      getc
      com.Li.servlet.GetServlet
   
   
      getc
      /getc
   

以上就是全部内容,下面开始测试。 

因为每次打开都是localhost:8080/s2。当时很好奇s2是哪来的(时间长忘了)。所以找了一下s2。

s2是在这里配的:

 

 

开始运行测试: 

 

先进入hello使得username有值 

 

得到输出: 

 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943598.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号