@[TOC]Httpservlet
数据存储于数据共享
Servlt 可通过ServltContext 对象,上下文对象,存储数据,
提示:以下是本篇文章正文内容,下面案例可供参考
一、编写一个类继承要让一个普通的java类变成Servlet,最简单的方法就是继承HttpServlet,
二、使用步骤 1.编写代码代码如下(示例):
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;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//通过ServletContext 存储数据
ServletContext context =this.getServletContext();
context.setAttribute("username","输出中文名字");
//通过response 对象存储数据,返回输出html代码
}
}
2.读入数据
代码如下(示例):
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 MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取存储在ServletContext上下文中的数据
ServletContext context = this.getServletContext( );
String username = String.valueOf(context.getAttribute("username"));
System.err.println(username);
}
}
需要注意的是一定要先触发HelloServlet 的doGet()方法,保证username set后,在执行MyServelt中的do Get()方法,才能读取出放入ServletContext中的值,否则值输出为null
3.在web.xml中配置Servlethelloword org.lsh.servlet.HelloServlet helloword /hello Myservlet org.lsh.servlet.MyServlet Myservlet /myservlet
总结
重点:一定要新进行set 然后才能正确的 get 到值
- 创建两个普通的java 类,都继承HttpServlet,
- 一个servlet 中存放数据,在另外一个Servlet中获取数据,都通过ServltContext 对象,获取或设置,可以把ServletContext 当成Servelt的容器
- 在Web.xml 文件 中配置Servlet,



