ServletContext的使用需要多个对象,任何一个对象传输数据后,其余的对象都可以取用改数据
HelloServlet传输一个名字
package com.su.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;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
public class HelloServlet extends HttpServlet {
//由于get和post知识请求实现的不同方式,谁调用谁都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getServletConfig(); servlet配置
// this.getInitParameter(); 初始化参数
// this.getServletContext(); servlet上下文
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
ServletContext servletContext = this.getServletContext();
String name="苏";
servletContext.setAttribute("username",name);
//将一个数据保存在ServletContext中,名字为ServletContext,名字为username,值rname
PrintWriter writer = resp.getWriter();
writer.print("名字是"+name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
GetName用来获取别的ServletContext对象传输的数据
package com.su.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "Servlet", value = "/Servlet")
public class GetName extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决中文乱码设置格式
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
ServletContext context = this.getServletContext();
String n = (String) context.getAttribute("username");
response.getWriter().print("名字是"+n);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
配置两个Servlet的web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
<!--set名字的配置-->
<!--web.xml是配置web的核心应用 这是注释-->
<!--
注册serverlet
<servlet>
<servlet-name></servlet-name>
</servlet>
一个servelet一个映射
<servlet-mapping>
<servlet-name></servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.su.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!--get名字的配置-->
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>com.su.servlet.GetName</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
</web-app>
运行结果如下:
使用HelloServlet存入数据
使用GetName取出数据