在文件目录下创建一个新的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有值
得到输出:



