Same
cn.iu.HelloServlet
Same
/hello
Httpservlet类
重写doGet()和doPost(),通常doPost()调用doGet()。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
在doGet()方法里写。
getServletContext();上下文对象,一个Servlet存放,另一个取,实现数据共享。
存
// this.getInitParameter(); 初始化参数
// this.getServletConfig(); Servlet配置
// this.getServletContext(); Servlet上下文
ServletContext servletContext = this.getServletContext();
String userName = "IU";
servletContext.setAttribute("username",userName); //将一个数据保存在了ServletContext中。键值对形式。
取
在取的类里写
ServletContext servletContext = this.getServletContext();
String username = (String)servletContext.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("李知恩:" + username);